On delete set null creating table in mysql - mysql

I am to create a table named patientmedicinecategory . as given below:-
CREATE TABLE patientmedicinecategory
(
pmc int(11) NOT NULL AUTO_INCREMENT,
patient_id int(11) NOT NULL,
med_id int(3) NOT NULL,
cat_id int(3) NOT NULL,
testname varchar(100) NOT NULL,
PRIMARY KEY(pmc),
UNIQUE KEY(patient_id, med_id,cat_id,testname),
FOREIGN KEY(patient_id) REFERENCES patient(patient_id) ON UPDATE CASCADE ON DELETE
CASCADE,
FOREIGN KEY(med_id) REFERENCES medicine(med_id) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY(cat_id) REFERENCES category(cat_id) ON UPDATE CASCADE ON DELETE SET NULL
)ENGINE=InnoDB;
my patient table is :-
CREATE TABLE patient
(
patient_id int NOT NULL AUTO_INCREMENT,
salutation ENUM('Mr.','Mrs.','Miss.','Dr.') NOT NULL,
name varchar(50) NOT NULL,
email_id varchar(100),
year int(4) NOT NULL,
month int(3),
day int(3),
sex ENUM('M','F') NOT NULL,
contactno varchar(50),
PRIMARY KEY(patient_id)
)ENGINE=InnoDb;
medicine table is :-
CREATE TABLE medicine
(
med_id int(3) NOT NULL,
name varchar(40) NOT NULL,
PRIMARY KEY (med_id)
)ENGINE=InnoDB;
category table is :-
CREATE TABLE category
(
cat_id int(3) NOT NULL,
name varchar(20) NOT NULL,
PRIMARY KEY (cat_id)
)ENGINE=InnoDB;
But when i try to create this it give the error:-
ERROR 1005 (HY000): Can't create table 'nutech3.patientmedicinecategory' (errno: 150)
I have tried a lot but could not success . please help me . Thanks in advance

If you log in as root and run SHOW ENGINE INNODB STATUS you'll see that the exact error message is this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
130405 11:55:42 Error in foreign key constraint of table test/patientmedicinecategory:
FOREIGN KEY(cat_id) REFERENCES category(cat_id) ON UPDATE CASCADE ON DELETE SET NULL
)ENGINE=InnoDB:
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL.
This is the offending line:
FOREIGN KEY(cat_id) REFERENCES category(cat_id) ON UPDATE CASCADE ON DELETE SET NULL
MySQL cannot make patientmedicinecategory.cat_id NULL because its defined this way:
cat_id int(3) NOT NULL,
Your options are either:
Allow cat_id to be NULL
Set a different ON DELETE condition

Related

SQL Key Column doesn't exist when ALTER TABLE

ALTER TABLE book
ADD FOREIGN KEY (category_id)
REFERENCES category (category_id)
ON DELETE CASCADE
ON UPDATE CASCADE;
Whenever I run this ALTER TABLE statement, it keeps coming back with, "Error Code: 1072. Key column 'category_id' does not exist."
I'm sure this is an easy fix, but I'm having problems adding a foreign key to one of my tables. I just started learning SQL last week so any help would be appreciated!
My CREATE TABLE statements are as follows:
CREATE TABLE IF NOT EXISTS book
(book_id INT not null PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) not null,
description TEXT not null,
price DEC(18,2) not null
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS category
(category_id INT not null PRIMARY KEY AUTO_INCREMENT,
code1 VARCHAR(20) not null,
name1 VARCHAR(100) not null
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS category
(category_id INT not null PRIMARY KEY AUTO_INCREMENT,
code1 VARCHAR(20) not null,
name1 VARCHAR(100) not null
) ENGINE=InnoDB;
This Table has the Primay Key category_id but below table has no Column
as "category_id" which is being referenced in the Alter Command.Add
Column "category_id in below table and then execute Alter command.
CREATE TABLE IF NOT EXISTS book
(book_id INT not null PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) not null,
description TEXT not null,
price DEC(18,2) not null
) ENGINE=InnoDB;
Here is the complete script then
CREATE TABLE IF NOT EXISTS book
(book_id INT not null PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) not null,
description TEXT not null,
price DEC(18,2) not null,
category_id INT not null
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS category
(category_id INT not null PRIMARY KEY AUTO_INCREMENT,
code1 VARCHAR(20) not null,
name1 VARCHAR(100) not null
) ENGINE=InnoDB;
ALTER TABLE book
ADD FOREIGN KEY (category_id)
REFERENCES category (category_id)
ON DELETE CASCADE
ON UPDATE CASCADE;

mysql creating table foreign key

I've created a table :
CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY
,uName VARCHAR(50)
,uSecondName VARCHAR(50)
,eMail VARCHAR(50)
)
After this I even insert some data without any problems. But when I've tried to create new table with FOREIGN KEY referenced to users.id I've got an error:
CREATE TABLE posts(
id INT(6) AUTO_INCREMENT NOT NULL
,pTitle VARCHAR(155) NOT NULL DEFAULT 'not_set'
,pText TEXT
,pAuthor INT(6)
,PRIMARY KEY(id)
,CONSTRAINT fk_PerAuthor FOREIGN KEY (pAuthor)
REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE
);
Did I miss something?

Cannot add foreign key constraint - MySQL ERROR 1215 (HY000)

I am trying to create database for gym management system, but I can't figure out why I am getting this error. I've tried to search for the answer here, but I couldn't find it.
ERROR 1215 (HY000): Cannot add foreign key constraint
CREATE TABLE sales(
saleId int(100) NOT NULL AUTO_INCREMENT,
accountNo int(100) NOT NULL,
payName VARCHAR(100) NOT NULL,
nextPayment DATE,
supplementName VARCHAR(250),
qty int(11),
workoutName VARCHAR(100),
sDate datetime NOT NULL DEFAULT NOW(),
totalAmount DECIMAL(11,2) NOT NULL,
CONSTRAINT PRIMARY KEY(saleId, accountNo, payName),
CONSTRAINT FOREIGN KEY(accountNo) REFERENCES accounts(accountNo) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(payName) REFERENCES paymentFor(payName) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(supplementName) REFERENCES supplements(supplementName) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(workoutName) REFERENCES workouts(workoutName) ON DELETE CASCADE ON UPDATE CASCADE
);
ALTER TABLE sales AUTO_INCREMENT = 2001;
Here is the parent tables.
CREATE TABLE accounts(
accountNo int(100) NOT NULL AUTO_INCREMENT,
accountType VARCHAR(100) NOT NULL,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(60) NOT NULL,
birthdate DATE NOT NULL,
gender VARCHAR(7),
city VARCHAR(50) NOT NULL,
street VARCHAR(50),
cellPhone VARCHAR(10),
emergencyPhone VARCHAR(10),
email VARCHAR(150) NOT NULL,
description VARCHAR(350),
occupation VARCHAR(50),
createdOn datetime NOT NULL DEFAULT NOW(),
CONSTRAINT PRIMARY KEY(accountNo)
);
ALTER TABLE accounts AUTO_INCREMENT = 1001;
CREATE TABLE supplements(
supplementId int(100) NOT NULL AUTO_INCREMENT,
supplementName VARCHAR(250) NOT NULL,
manufacture VARCHAR(100),
description VARCHAR(150),
qtyOnHand INT(5),
unitPrice DECIMAL(11,2),
manufactureDate DATE,
expirationDate DATE,
CONSTRAINT PRIMARY KEY(supplementId, supplementName)
);
ALTER TABLE supplements AUTO_INCREMENT = 3001;
CREATE TABLE workouts(
workoutId int(100) NOT NULL AUTO_INCREMENT,
workoutName VARCHAR(100) NOT NULL,
description VARCHAR(7500) NOT NULL,
duration VARCHAR(30),
CONSTRAINT PRIMARY KEY(workoutId, workoutName)
);
ALTER TABLE workouts AUTO_INCREMENT = 4001;
CREATE TABLE paymentFor(
payId int(100) NOT NULL AUTO_INCREMENT,
payName VARCHAR(100) NOT NULL,
amount DECIMAL(11,2),
CONSTRAINT PRIMARY KEY(payId, payName)
);
ALTER TABLE paymentFor AUTO_INCREMENT = 5001;
Can you guys help me with this problem? Thanks.
If you ever want to find out, why that error was , all you have to do is run below command and look for "LATEST FOREIGN KEY ERROR"
Command to run :-
mysql> SHOW ENGINE INNODB STATUS
You will know the reason for your such errors.
For a field to be defined as a foreign key, the referenced parent field must have an index defined on it.
As per documentation on foreign key constraints:
REFERENCES parent_tbl_name (index_col_name,...)
Define an INDEX on workouts.workoutName, paymentFor.paymentName, and supplements.supplementName respectively. And make sure that child column definitions must match with those of their parent column definitions.
Change workouts table definition as below:
CREATE TABLE workouts(
workoutId int(100) NOT NULL AUTO_INCREMENT,
workoutName VARCHAR(100) NOT NULL,
description VARCHAR(7500) NOT NULL,
duration VARCHAR(30),
KEY ( workoutName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(workoutId, workoutName)
);
Change supplements table definition as below:
CREATE TABLE supplements(
supplementId int(100) NOT NULL AUTO_INCREMENT,
supplementName VARCHAR(250) NOT NULL,
manufacture VARCHAR(100),
description VARCHAR(150),
qtyOnHand INT(5),
unitPrice DECIMAL(11,2),
manufactureDate DATE,
expirationDate DATE,
KEY ( supplementName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(supplementId, supplementName)
);
Change paymentFor table definition as below:
CREATE TABLE paymentFor(
payId int(100) NOT NULL AUTO_INCREMENT,
payName VARCHAR(100) NOT NULL,
amount DECIMAL(11,2),
KEY ( payName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(payId, payName)
);
Now, change child table definition as below:
CREATE TABLE sales(
saleId int(100) NOT NULL AUTO_INCREMENT,
accountNo int(100) NOT NULL,
payName VARCHAR(100) NOT NULL,
nextPayment DATE,
supplementName VARCHAR(250) NOT NULL,
qty int(11),
workoutName VARCHAR(100) NOT NULL,
sDate datetime NOT NULL DEFAULT NOW(),
totalAmount DECIMAL(11,2) NOT NULL,
CONSTRAINT PRIMARY KEY(saleId, accountNo, payName),
CONSTRAINT FOREIGN KEY(accountNo)
REFERENCES accounts(accountNo)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(payName)
REFERENCES paymentFor(payName)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(supplementName)
REFERENCES supplements(supplementName)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(workoutName)
REFERENCES workouts(workoutName)
ON DELETE CASCADE ON UPDATE CASCADE
);
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION
Foreign Keys are a way of implementing relationships/constraints between columns in different tables.
There are different categories of constraints that influence how they’re enforced when a row is updated or deleted from the parent table:
◾Cascade: If a row is deleted from the parent then any rows in the child table with a matching FK value will also be deleted. Similarly for changes to the value in the parent table.
◾Restrict: A row cannot be deleted from the parent table if this would break a FK constraint with the child table. Similarly for changes to the value in the parent table.
◾No Action: Very similar to “Restrict” except that any events/triggers on the parent table will be executed before the constraint is enforced – giving the application writer the option to resolve any FK constraint conflicts using a stored procedure.
◾Set NULL: If NULL is a permitted value for the FK column in the child table then it will be set to NULL if the associated data in the parent table is updated or deleted.
◾Set Default: If there is a default value for the FK column in the child table then it will be used if the associated data in the parent table is updated or deleted. Note that this is not implemented in this version – the constraint can be added to the schema but any subsequent deletion or update to the column in the parent table will fail.
Some times you will get this error "#1215 - Cannot add foreign key constraint" because of table TYPE (InnoDB, MyISAM,..) mismatch.
So change your table type into same and try applying for foreign key constraint
mysql> ALTER TABLE table_name ENGINE=InnoDB;
mysql> ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
This might work for some people. Simply add the default character set as utf8
DEFAULT CHARACTER SET = utf8;
I was getting the same error. The reason was I was referring to a column in a table created with charset utf8 from a table created using charset latin.
The tables created using mySQL workbench create table utility have default charset latin.
Easy approach to find this out if you are using workbench is to view the table create statement of any table. You will have the default charset string at the end.
I'm not answering the above question but just for people who will run into the same mysql error.
All I did was to change the referenced table engine to innodb.
I encounter this error I add foreign key constraint for a column that has 'not null constraint' but I specified the 'on delete set null' in the foreign constraint. This is a contradiction that it may not be obvious at first.
Here are my two tables:
CREATE TABLE study (
id int(11) NOT NULL AUTO_INCREMENT primary key,
name varchar(100) NOT NULL,
introduction text,
objective varchar(250) DEFAULT NULL,
method text,
result text,
conclusion varchar(250) DEFAULT NULL,
future_action varchar(100) DEFAULT NULL
);
drop table client_study;
CREATE TABLE client_study (
id int(11) NOT NULL AUTO_INCREMENT primary key,
client_id int(11),
study_id int(11) not null, --If delete 'not null' error goes away!
contact_person int(11),
effective_date datetime DEFAULT CURRENT_TIMESTAMP,
trial_site int(11) DEFAULT NULL,
UNIQUE KEY unqidx_client_study (client_id,study_id)
);
ALTER TABLE client_study
ADD CONSTRAINT FOREIGN KEY (study_id) REFERENCES study(id)
ON DELETE SET NULL ON UPDATE CASCADE;
ERROR 1215 (HY000): Cannot add foreign key constraint
If you remove the NOT NULL constraint on the study_id column in the client_study table, the foreign key can be added. The other alternative is to keep the not null constraint on the client_table, but modify the foreign key definition to on delete no action or other choices.

MySQL Table order is correct, data types match, so why do I get ERROR 1005 (HY000)

I have several tables and several of them reference each other to create many-to-many relationships. I realize data types must match and table order matters when creating the foreign keys. I think I have all that accounted for. So why am I getting the ERROR 1005 (HY000) in the following:
CREATE TABLE USER (
id INT UNSIGNED NOT NULL auto_increment PRIMARY KEY,
userName VARCHAR(20) NOT NULL UNIQUE,
email VARCHAR(25) NOT NULL UNIQUE,
firstName VARCHAR(15) NOT NULL,
lastName VARCHAR(20) NOT NULL,
salt CHAR(10) NOT NULL,
HASH CHAR(40)
)ENGINE=InnoDB;
CREATE TABLE PRODUCT (
id INT UNSIGNED NOT NULL auto_increment PRIMARY KEY,
prodName VARCHAR(50) NOT NULL UNIQUE,
price DECIMAL(6,2),
availability BOOLEAN,
description VARCHAR(150) NOT NULL,
size VARCHAR(20),
weight VARCHAR(10)
)ENGINE=InnoDB;
CREATE TABLE USERENTERSPRODUCT (
userID INT UNSIGNED NOT NULL,
prodID INT UNSIGNED NOT NULL,
PRIMARY KEY (userID, prodID),
FOREIGN KEY (userID) REFERENCES USER(id) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (prodID) REFERENCES PRODUCT(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
CREATE TABLE USERENTERSPRODUCT (
userID INT UNSIGNED NOT NULL,
prodID INT UNSIGNED NOT NULL,
PRIMARY KEY (userID, prodID),
FOREIGN KEY (userID) REFERENCES USER(id) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (prodID) REFERENCES PRODUCT(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
You are specifying ON DELETE SET NULL here, but at the same time both columns have NOT NULL specified as well … that obviously can’t work.
So either remove the NOT NULL from the column definition, or change ON DELETE SET NULL to whatever matches you needs best. (Normally that should be CASCADE as well, that makes the most sense.)

Mysql create table with multiple foreign key on delete set null

I am trying to create a database with multiple foreign keys with delete/ update constraints, but I got a error code 1005 with following sql scripts:
CREATE TABLE Worker (
WorkerID smallint auto_increment,
WorkerType varchar(45) NOT NULL,
WorkerName varchar(45) NOT NULL,
Position varchar(45) NOT NULL,
TaxFileNumber int NOT NULL,
Address varchar(100) ,
Phone varchar(20) ,
SupervisorID smallint ,
PRIMARY KEY (WorkerID),
FOREIGN KEY (SupervisorID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
CREATE TABLE Grape (
GrapeID smallint NOT NULL,
GrapeType varchar(45) NOT NULL,
JuiceConversionRatio int,
StorageContainer ENUM('Stainless Steel Tank','Oak Barrel'),
AgingRequirement int,
PRIMARY KEY (GrapeID)
)Engine=InnoDB;
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint NOT NULL,
GrapeID smallint NOT NULL,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
The error code says that fail to create the Vineyard table, I just want to know the proper format for creating multiple foreign keys with delete/update control.
Your foreign key rule is ON DELETE SET NULL but your column definition is NOT NULL.
Either change your column definition and remove the NOT NULL part or overthink your foreign key rule. That works:
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint,
GrapeID smallint,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
SQLFiddle demo
Try with create table(innoDB enginer) without foreign key and use the update table with constraint syntax, for example:
ALTER TABLE `vineyard`
ADD CONSTRAINT `relation_farmer_has_many_vineyards`
FOREIGN KEY (`farmer_id`)
REFERENCES `worker` (`worker_id`)
ON DELETE SET NULL
ON UPDATE CASCADE;
Reference:
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
Trick: is not recommended to use capital letters(or camel case) in the names of the tables that the behavior differs from the operating system being used:
http://dev.mysql.com/doc/refman/5.1/en/identifier-case-sensitivity.html
Visit :
https://developer.android.com/training/basics/data-storage/databases.html#DefineContract
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Visit :
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
CREATE TABLE `ffxi_characterJob` (
`serverID` int(11) NOT NULL,
`userid` int(10)unsigned NOT NULL,
`characterName` varchar(255) NOT NULL,
`jobAbbr` char(4) NOT NULL,
`jobLevel` int(11) default '0',
PRIMARY KEY (`serverID`,`userid`,`characterName`,`jobAbbr`),
INDEX (`jobAbbr`),
CONSTRAINT FOREIGN KEY (`serverID`,`userid`,`characterName`) REFERENCES `ffxi_characters` (`serverID`,`userid`,`characterName`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (`jobAbbr`) REFERENCES `ffxi_jobType` (`jobAbbr`) ON DELETE CASCADE ON UPDATE CASCADE
) TYPE=InnoDB;