Foreign Key constraint error even without a foreign key - mysql

I am getting the following error:
Error Code: 1215. Cannot add foreign key constraint
This happens even if I remove all foreign key constraints. timeline table does exist in the database, so that is not the issue.
Can't seem to figure out what would cause this problem
USE study;
CREATE TABLE IF NOT EXISTS timelineStage(
timelineStageID INT NOT NULL AUTO_INCREMENT,
timelineID TINYINT NOT NULL,
stageName VARCHAR(100) NOT NULL,
stagePredecessorID INT NULL,
isStartup TINYINT NOT NULL DEFAULT 0,
timelineStageNotes VARCHAR(500) NULL,
recCreatedByUserID INT NOT NULL,
recCreatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
recUpdatedByUserID INT NOT NULL,
recUpdatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (timelineStageID),
UNIQUE KEY IX_U_timelineStage_stageName(stageName, timelineID),
UNIQUE KEY IX_U_timelineStage_stagePredecessor(stagePredecessorID, timelineID),
CONSTRAINT FK_timelineStage_timelineID
FOREIGN KEY (timelineID)
REFERENCES timeline(timelineID)
ON UPDATE CASCADE,
CONSTRAINT FK_timelineStage_stagePredecessorID
FOREIGN KEY (stagePredecessorID)
REFERENCES timelineStage(timelineStageID)
ON UPDATE CASCADE,
CONSTRAINT FK_timelineStage_recCreatedByUserID
FOREIGN KEY (recCreatedByUserID)
REFERENCES customer.user(userID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_timelineStage_recUpdatedByUserID
FOREIGN KEY (recUpdatedByUserID)
REFERENCES customer.user(userID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ADDING Timeline and customer.user
USE study;
CREATE TABLE timeline(
timelineID TINYINT NOT NULL AUTO_INCREMENT,
timelineName VARCHAR(100) NOT NULL,
timelineNotes VARCHAR(500) NULL,
recCreatedByUserID INT(11) NOT NULL,
recCreatedTimeUTC DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
recUpdatedByUserID INT(11) NOT NULL,
recUpdatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (timelineID)
)
CREATE TABLE customer.user(
userID INT NOT NULL AUTO_INCREMENT,
firstName VARCHAR(100) NOT NULL,
lastName VARCHAR(100) NOT NULL,
emailAddress VARCHAR(100) NOT NULL,
PRIMARY KEY (userID))

The problem was with neither of the other tables. It was is study table (another table).
timelineStageID was set to TINYINT and in timelineStage table timelineStageID was set to INT.
Matching all to INT fixed the problem.

Carefully check every references clause whether the referenced column really is present in the table.
Also try to first create the table and then add the constraints one by one so you exactly know which one failed.

The problem is about this code: REFERENCES customer.user
You cannot create a foreign key constraint referencing a table in another database.

Related

MySQL duplicate key in table

I have an error with the following SQL query and I'm not sure how to fix it. The error message is:
"Error Code: 1022. Can't write; duplicate key in table
't_course_catalog'"
Here is the query:
CREATE TABLE IF NOT EXISTS `TrainingPlan`.`T_Course_Catalog` (
`CC_ID` INT NOT NULL AUTO_INCREMENT,
`ID_Catalog_Level` INT NOT NULL,
`Catalog_Name` VARCHAR(50) NOT NULL,
`ID_Delivery_Method` INT NOT NULL,
`Created_Date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Created_By` VARCHAR(8) NOT NULL,
`Modified_Date` TIMESTAMP NULL,
`Modified_By` VARCHAR(8) NULL,
`Deleted` TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`CC_ID`),
INDEX `fk_cl_idx` (`ID_Catalog_Level` ASC),
INDEX `fk_dm_idx` (`ID_Delivery_Method` ASC),
CONSTRAINT `fk_cl`
FOREIGN KEY (`ID_Catalog_Level`)
REFERENCES `TrainingPlan`.`T_Catalog_Level` (`CL_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_dm`
FOREIGN KEY (`ID_Delivery_Method`)
REFERENCES `TrainingPlan`.`T_Delivery_Method` (`DM_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
It should be no problem to reference the foreign keys because the reference table exists.
Try renaming your constraints, they are probably duplicated somewhere in your database.
Example :
fk_cl becomes fk_course_catalog_cl
fk_dm become fk_course_catalog_dm
Or w/e alternative name you want it to be.

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;

Shortcut Assign Primary Key while create table

What is the right way to assign primary key with shortcut query while creating table?
Here is the example how my shortcut it is:
create table booking_product (
`id` int(10) not null constraint `booking_product_id` primary key auto_increment ,
`bookingId` int(10) not null,
`serviceId` int(10) not null,
`date` date not null,
`price` decimal(30,15) not null,
`qty` int(1) not null,
`currencyId` int(10) not null,
`total` decimal(30,15) not null,
`roomInclusion` text null default null,
foreign key booking_product(bookingId) references booking(id) on update cascade on delete cascade,
foreign key booking_product(serviceId) references service(id) on update cascade on delete set null,
foreign key booking_product(currencyId) references currency(id) on update cascade on delete set null
) engine = InnoDB;
notice on line 2 I tried to assign primary key, but this query is wrong and produce error. If I try to only use id int(10) not null primary key auto_increment , I get error: Duplicate key name 'booking_product'
If you use constraint booking_product_id, you don't get errors about Duplicate key name 'booking_product' because the SQL parser stops at the first error.
Drop constraint booking_product_id and use
foreign key bookingId_fk(bookingId) references booking(id)
on update cascade
on delete cascade,
foreign key serviceId_fk(serviceId) references service(id)
on update cascade
on delete set null,
foreign key currencyId_fk(currencyId) references currency(id)
on update cascade
on delete set null
I know you picked an answer but when I simplified just your create statement to the code below I got it to work. Now with the added 'drop constraint' request by Oswald you might have everything you want:
create table booking_product (
id int(10) not null auto_increment,
PRIMARY KEY(id), <<<<< this worked for me...
bookingId int(10) not null,
serviceId int(10) not null,
date date not null,
price decimal(30,15) not null,
qty int(1) not null,
currencyId int(10) not null,
total decimal(30,15) not null,
roomInclusion text null default null)
Again I am only approaching the question from what you asked which was assigning a primary.
Hope this helps.

Foreign Key not working: Error code 1005, SQL state HY000: Can't create table

I have two tables I have created and I'm adding the foreign key constraint after the fact.
The two tables are defined as such:
CREATE TABLE `user` (
`user_id` int(11) NOT NULL auto_increment,
`user_ad_id` varchar(500) default NULL,
`user_name` varchar(100) NOT NULL,
`login_id` varchar(100) default NULL,
`email` varchar(256) NOT NULL,
`personal_config` int(10) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS personal_config (
config_id INT(10) NOT NULL AUTO_INCREMENT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
configuration TEXT(25600) NOT NULL,
PRIMARY KEY (config_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE personal_config ADD CONSTRAINT personal_config_fk_user FOREIGN KEY
(config_id) REFERENCES user(personal_config);
And I keep getting the same error but can't figure it out. I've searched all the related threads to this.
Your FK config_id can't be an autoincrement field, that doesn't make much sense right? That field reflects a value in the foreign table, it cannot be set arbitrarily in the local table.
I think this is what you want:
ALTER TABLE user ADD CONSTRAINT personal_config_fk_user FOREIGN KEY (personal_config) REFERENCES personal_config(config_id);
Your ALTER TABLE statement is backward. Since personal_config.config_id is an auto_increment primary key, the foreign key should be defined in the users table against personal_config, not in personal_config against the users table.
ALTER TABLE users ADD CONSTRAINT user_fk_personal_config
FOREIGN KEY (personal_config)
REFERENCES personal_config(config_id);
if you set your user table field personal_config is primary key then it is possible to execute
CREATE TABLE IF NOT EXISTS personal_config (
config_id INT(10) NOT NULL AUTO_INCREMENT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
configuration TEXT(25600) NOT NULL,
PRIMARY KEY (config_id), FOREIGN KEY
(config_id) REFERENCES user(personal_config)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

Foreign key constraint is incorrectly formed?

I got this error when create table: Foreign key constraint is incorrectly formed?
create table comment(
Comment_ID int UNSIGNED AUTO_INCREMENT not null,
User_1 varchar(50) not null,
Note_ID int(11) UNSIGNED not null,
PRIMARY key(Comment_ID),
CONSTRAINT `fk_1` FOREIGN KEY (`User_1`) REFERENCES `user` (`Dev_ID`),
CONSTRAINT `fk_2` FOREIGN KEY (`User_2`) REFERENCES `user` (`Dev_ID`),
CONSTRAINT `fk_3` FOREIGN KEY (`Note_ID`) REFERENCES `note`(`Note_ID`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
it's OK when I remove fk_3.
This my note table
CREATE TABLE `note` (
`Dev_ID` varchar(50) NOT NULL,
`Note_ID` int(11) UNSIGNED NOT NULL,
`Title` varchar(200) NOT NULL,
`Time` datetime NOT NULL,
`Mood` int(11) NOT NULL,
`Body` varchar(3000) NOT NULL,
`Visible` tinyint(1) NOT NULL DEFAULT '1',
`Share` tinyint(1) NOT NULL DEFAULT '0',
`Update` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`Dev_ID`,`Note_ID`),
CONSTRAINT `fk_note_user` FOREIGN KEY (`Dev_ID`)
REFERENCES `user` (`Dev_ID`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Thanks for help!
That's because the primary key of the note table is (Dev_ID,Note_ID) but you are only referencing one of those columns (Note_ID) in your constraint.
A FK constraint must always consist of all PK columns.
Also make sure that both tables are innoDB.
In addition to the answers that have been given, you would also get this error if the field types did not match. For example, if you tried to create a foreign key constraint between a varchar field and an int field.
This problem occur because the column
`Note_ID` int(11) UNSIGNED NOT NULL
Is neither primary nor unique.
Just make it
`Note_ID` int(11) UNSIGNED NOT NULL UNIQUE
And it will work.
One more addition: charsets of the fields must match.
In the referenced table I had ascii as a default charset: DEFAULT CHARSET=ascii was reported by show create table. I tried to create the referencing table with DEFAULT CHARSET=utf and I got 'Foreign key constraint is incorrectly formed'.
After I changed this to DEFAULT CHARSET=ascii on the new table (the referencing one), it was created successfully.
Ensure the collation is the same on both fields. I had the same problem when one was latin-general-ci and the other was utf8_unicode_ci. Not sure why the collation changed on the one table but fixing this resolved the issue.