How do I create table schema in MySQL which populates data dynamically? - mysql

I have a php page where the user enters the following details
Name
Age
But in the database, I want to have an additional column that automatically inserts data with the combination of entered data as shown below for Code column.
Key
Name
Age
Code
1
Mike
28
MIKE128
2
Raj
32
RAJ232
So I have altered my table as follow
ALTER TABLE Employee ADD COLUMN Code;
UPDATE Employee SET Code = CONCAT(Key,Name,Age);
But this updates only the existing data for existing data,and shows NULL for newly entered data. What is the command I shall use to change the schema so that whenever I add new data automatically it updates the Code column
Below is my try, which is failed
CREATE TABLE `Employee` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) NOT NULL,
`Age` int(2) NOT NULL,
`Combined` varchar(10) AS (`Name` + `id` + `Age`) Code,
PRIMARY KEY (`id`)
);
ERROR 1064 (42000) at line 2: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Code,
PRIMARY KEY (id)
)' at line 4
Note: I DO NOT want to concate and supply data from the front end.
Note: This is just example as I can not post real data.

You can setup trigger for dynamic default value
CREATE TRIGGER Employee_code_trigger
BEFORE INSERT ON Employee
FOR EACH ROW
SET NEW.Code = IFNULL(NEW.Code, CONCAT(NEW.Key, NEW.Name, NEW.Age));

Related

getting error on insertion in mysql

i have created a table in mysql named as student with 2 columns named as "S-id int not null auto_increment 14012040" and "S-name varchar(45) not null unique" "primary key(S-id)"....
the table was successfully created..but after inserting one record into db ,on the next insertion it shows error like "dupliction of primary key is not allowed"...plz hlp me whta should i do..
in th below i am posting the screen shots....
creating table.
[1st insertion successfully addesd][2]
getting error
Your primary key S-id has a default value (14012040).
You only inserts values for S-name and studentcol columns therefore it will use the S-ids default value again and again.
When it runs first it can use the default value because it is not exists in the table. But second time it will throw an error.
You should use auto increment for S-id as Álvaro Touzón said.
UPDATE:
According to your comment, here is the working create script:
CREATE TABLE student (
S_id INT NOT NULL AUTO_INCREMENT
,S_name VARCHAR(45) NOT NULL
,PRIMARY KEY (S_id)
,UNIQUE INDEX S_name_UNIQUE(S_name ASC)
) AUTO_INCREMENT=14012040;
Working SQL fiddle here.

Can't set a default value to INT(11) altering table

I am trying to alter a table and set a default value for a nullable column. But i get the following error.
Here is the command:
ALTER TABLE `questiontboard`.`questions`
CHANGE COLUMN `status` `status` (11) NULL DEFAULT 1 ;
Here is the error:
ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(11) NULL DEFAULT 1' at line 2
SQL Statement:
ALTER TABLE `questionboard`.`questions`
CHANGE COLUMN `status` `status` (11) NULL DEFAULT 1
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'question' already exists
What am i doing wrong?
You forgot the data type. Did you mean
ALTER TABLE `questiontboard`.`questions`
CHANGE COLUMN `status` `status` INT(11) NULL DEFAULT 1 ;
^^^
Your query should be this:
ALTER TABLE `questiontboard`.`questions`
CHANGE COLUMN `status` `status` int(11) NULL DEFAULT 1 ;
^^ here add int as you want the datatype
You are missing datatype of field in the query.
I got the same error when altering a table. I did the exact same thing you did (minus the code typo).
I got the error when altering a column from a SMALLINT to a varchar(n). It gives the "1050 Table already exists..." error. The error was confusing. Of course the table exists, that's why I'm trying to alter it!
In the end, I found out that the problem was that my new varchar(2) was not big enough to hold all the original smallint data. I had one row that had a 4 digit number, so varchar(2) wouldn't work. I changed it to use varchar(4), and it worked.
ALTER TABLE omiccom_wp.myTable
CHANGE COLUMN myColumn myColumn VARCHAR(2) NOT NULL DEFAULT '0' ;

MySQL: how to create a trigger that add not-null constraint?

I have created the customer table that has a trigger that not allow null value on the customer_id column. it looks like:
create table customer(
customer_id varchar(20) UNIQUE,
customer_name varchar(15) NOT NULL,
password varchar(10) NOT NULL,
social_number varchar(14) not null,
phone_number varchar(13) NOT NULL,
email varchar(30) NOT NULL,
address varchar(50) NOT NULL,
primary key ( social_number )
);
But, creating the following trigger causes this error.
create trigger null_checker
on customer
after insert
as
delete from customer
where customer_id is null;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'on customer after insert as delete from customer where customer_id is null' at line 1
What's wrong with? I could add not-null constraint using not null specifier. but I am not allowed to do it because creating the trigger is a part of my assignment. Any help would be appreciated.
You need to use right syntax:
create trigger null_checker
after insert on customer
for each row
delete from customer
where customer_id is null;
But you cannot modify the same table from trigger.
A solution, without triggers, may be is change the sql_mode to avoid null values defined in your columns.
set sql_mode = 'TRADITIONAL';
That command says to MySQL “give an error instead of a warning” when inserting an incorrect value into a column, like inserting NULL to a 'NOT NULL column.
More info: http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html

Integrity constraint in MySQL to express "must have one primary attribute"

I have a 2-table schema which can be specified as follows:
CREATE TABLE MEMBERS
( membershipnumber int NOT NULL PRIMARY KEY,
firstname varchar(20) NOT NULL,
lastname varchar(20) NOT NULL,
email varchar(30) NOT NULL,
status varchar(15) NOT NULL DEFAULT 'unapproved',
);
CREATE TABLE TELEPHONENUMBERS
( telephone varchar(15) NOT NULL PRIMARY KEY,
membershipnumber INT NOT NULL REFERENCES MEMBERS(membershipnumber),
isprimary enum('0','1') NOT NULL DEFAULT '1'
);
I am trying to specify an integrity constraint to indicate that any individual member may have only one primary telephone number (i.e. telephonenumbers.isprimary='1') and any number of secondary telephone numbers.
Here is my current attempt:
ALTER TABLE MEMBERS
ADD CONSTRAINT oneprimary_ck CHECK (SELECT COUNT(isprimary)=1 FROM TELEPHONENUMBERS WHERE TELEPHONENUMBERS.membershipnumber = membershipnumber) IN '1';
However this yields the following syntax error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(isprimary)=0 FROM TELEPHONENUMBERS WHERE TELEPHONENUMBERS.membershipnumber=1 IN '1') IN ''
I'm assuming my approach is totally wrong, but am unsure how to proceed. Would it be better to do this using a trigger or is there a small alteration ot my approach that would work?
I am using server version: 5.5.30.
With many thanks,
Froskoy.
Does it work any better if you swap ...
ALTER TABLE MEMBERS ADD CONSTRAINT oneprimary_ck CHECK
(SELECT COUNT(isprimary)=1 FROM TELEPHONENUMBERS
WHERE TELEPHONENUMBERS.membershipnumber = membershipnumber) IN '1';
... with ...
ALTER TABLE MEMBERS ADD CONSTRAINT oneprimary_ck CHECK
(SELECT COUNT(isprimary) FROM TELEPHONENUMBERS
WHERE isprimary=1 AND TELEPHONENUMBERS.membershipnumber = membershipnumber) > 1;
... ?
Two things are wrong in your approach:
A check constraint cannot contain a subquery
Check constraints are not enforced by MySQL (not in 5.5 anyway)
What you can do, is create a trigger that raises an error. Here's an example:
https://stackoverflow.com/a/7189396/417194

Inserting a value into one table based on insert from another table

I have this table for users that stores their usernames and other data, thats done like this (stripped down):
CREATE TABLE `prod_users` (
`p_user_id` INT(11) NOT NULL AUTO_INCREMENT,
`p_user_name` VARCHAR(200) NOT NULL DEFAULT ''
`p_comp_name` VARCHAR(300) NOT NULL DEFAULT '',
PRIMARY KEY (`p_user_id`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
Each time a user signs up, he'll provide a company name as well.
There's another table called prod_profiles, which stores profile details like phone nos. fax nos. etc.
CREATE TABLE `prod_profiles` (
`pf_gen_id` INT(11) NOT NULL AUTO_INCREMENT,
`pf_user_id` INT(11) NOT NULL DEFAULT '0',
`pf_user_name` VARCHAR(200) NOT NULL DEFAULT ''
`pf_comp_name` VARCHAR(300) NOT NULL DEFAULT '',
PRIMARY KEY (`pf_gen_id`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
When a new user signs up and his details are added to prod_users, is it possible to automatically add his new user_id, user_name and comp_name details to prod_profile using MySql itself? Since each user will have a new p_user_id and we wont know it, it'll be difficult using php. Can this be achieved inside MySql itself without any problems?
It isn't difficult using PHP, since you have the LAST_INSERT_ID() available for use, be it via mysql_insert_id() or mysqli::$insert_id, PDO::lastInsertId() or whatever your API provides. As long as you call the two INSERT statements in immediate succession on the same script (it is connection dependent), MySQL will supply the correct p_user_id.
However, you can use an AFTER INSERT trigger to force MySQL to create the new row automatically:
CREATE TRIGGER build_profile AFTER INSERT ON prod_users
FOR EACH ROW
BEGIN
INSERT INTO prod_profiles
(pf_user_id, pf_user_name, pf_comp_name)
VALUES (NEW.p_user_id, NEW.p_user_name, NEW.p_comp_name)
END
Review the MySQL CREATE TRIGGER syntax reference for full details and options.
You can use the next mysql function: LAST_INSERT_ID(); which returns the last auto increased id.
Therefore , add a user and then add a prod_profile , while pf_user_id value will be the returned value of last_insert_id().
INSERT INTO `prod_users`(`p_user_name`,`p_comp_name`) VALUES('Dan' , 'Stackover')
INSERT INTO `prod_profiles`(`pf_user_id`,`pf_user_name`,`pf_comp_name`) VALUES(LAST_INSERT_ID(),'Dan','Stackover')
Please notice: I have to say , that storing the username and company_name twice for the same user in two different tables is a reall waste...
Consider re-thinking about your DB structre and logic.