Foreign key constraint is incorrectly formed? - mysql

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.

Related

Foreign Key constraint error even without a foreign key

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.

MySQL Error Code: 1215. Cannot add foreign key constraint (the datatypes of the two columns match)

I am trying to create a foreign key constraint to the existing table only to receive Error Code: 1215. Cannot add foreign key constraint. Below I include SHOW CREATE TABLE observation_log_status;, SHOW CREATE TABLE observation_log; outputs and the foreign key constraint statement that fails. I have checked (according to the suggestion here) that the datatypes of the two columns are the same (they are) and if the two columns were signed or unsigned (according to the suggestion here) (they are neither), but the error remains the same. I am using MySQL 5.7.17.
Thanks,
Aina.
EDIT: this is not a duplicate, but I am obliged now to explain how it is different. In the question that is meant to be the duplicate the OP didn't have the same datatype for the two columns, I do, as shown by my SHOW CREATE TABLE statements outputs.
*********************************SOLUTION**************************************
ANOTHER EDIT: As P.Salmon suggested the problem was indeed the ENGINE.
I solved it by running ALTER TABLE observation_log ENGINE = InnoDB;.
Then the ALTER TABLE observation_log_status ADD CONSTRAINT observation_log_fk FOREIGN KEY (aat_id) REFERENCES observation_log(aat_id); statement worked fine.
*********************************SOLUTION**************************************
SHOW CREATE TABLE observation_log;
observation_log, CREATE TABLE `observation_log` (
`aat_id` decimal(14,0) NOT NULL DEFAULT '0',
`utdate` date DEFAULT NULL,
`session` char(1) NOT NULL DEFAULT '',
...,
`aaoprgid` char(11) DEFAULT NULL,
PRIMARY KEY (`aat_id`),
KEY `obs_object` (`object`),
KEY `obs_utdate` (`utdate`),
KEY `obs_ra_dec` (`raj2000_int`,`decj2000_int`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
SHOW CREATE TABLE observation_log_status;
observation_log_status, CREATE TABLE `observation_log_status` (
`observation_log_status_id` int(11) NOT NULL AUTO_INCREMENT,
`aat_id` decimal(14,0) NOT NULL DEFAULT '0',
`data_needs_processing_status` tinyint(1) DEFAULT '1',
`data_file_transfer_status` tinyint(1) DEFAULT '0',
`megatable_update_status` tinyint(1) DEFAULT '0',
`data_file_search_attempt_count` int(11) DEFAULT '0',
`data_file_trasnfer_attempt_count` int(11) DEFAULT '0',
`megatable_update_attempt_count` int(11) DEFAULT '0',
`data_file_transfer_timer` int(11) DEFAULT '0',
`row_insert_time` datetime(6) DEFAULT CURRENT_TIMESTAMP(6),
PRIMARY KEY (`observation_log_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
The statement the generates the error:
ALTER TABLE observation_log_status ADD CONSTRAINT observation_log_fk FOREIGN KEY (aat_id) REFERENCES observation_log(aat_id);
aat_id` decimal(14,0) NOT NULL DEFAULT '0'
Try removing the default value. Foreign keys cannot have default value. Only those value present in the primary key can be accepted by foreign key

What is the cause for MySQL: Errorno 150

Can someone please explain the cause for the following error, 'Can't create table 'Activities' (errno: 150)'
I'm under the understading that the data types and lengths have to be the same, does is have anything to do with the auto increment?
Create Table `LinkMemberActivity` (
`LinkID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`MID` int(11) unsigned NOT NULL,
`AID` int(11) unsigned NOT NULL,
PRIMARY KEY (`LinkID`),
FOREIGN KEY (`MID`) REFERENCES Members(`MID`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
)
CREATE TABLE `Activities` (
`AID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(25) DEFAULT NULL,
`MaxCapacity` int(25) DEFAULT NULL,
`StartTime` time DEFAULT NULL,
`EndTime` time DEFAULT NULL,
PRIMARY KEY (`AID`),
FOREIGN KEY (`AID`) REFERENCES LinkMemberActivity(`AID`))
ENGINE=InnoDB DEFAULT CHARSET=latin1 );
You are trying to make a primary key column a foreign key dependent field. This is not only unusual but makes no sense in a datamodel, unless it is part of a composite key. Common practice has a column foreign key dependent on another tables primary key. Not sure what reasons you have for the way you designed your datamodel this way, but you can fix this problem by creating a not null autoincrement column named ID and make this column the primary key. Next remove autoincrement from aid.

mysql won't allow foreign key

Many people had this problem already, but there was no fitting solution in other posts.
I have two tables, one named "sales", the other named "host_flags". I would like to have a foreign key for host_flags.sales_id to sales.id, but mysql won't let me! I have primary indexes defined in each table, so I wonder why...
The host_flags table already has a foreign key on the column host_id, but even when I tried and created the foreign key for the sales id first, it wouldn't let me.
The tables look like:
CREATE TABLE `sales` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`creation` datetime DEFAULT NULL,
`lastupdate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
CREATE TABLE `host_flags` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`host_id` int(11) DEFAULT NULL,
`sales_id` int(11) DEFAULT NULL,
`creation` datetime DEFAULT NULL,
`lastupdate` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `host_id6` (`host_id`),
CONSTRAINT `host_id6` FOREIGN KEY (`host_id`) REFERENCES `hosts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `hosts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`creation` datetime NOT NULL,
`lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32225 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
I get this error message:
MySQL said: Can't create table 'primarydata.#sql-191_1' (errno: 150)
Thanks!
Charles
SOLUTION FOUND
All ints of the primary indexes have to be either signed or unsigned - not mixed.
Typically:
I like to declare the FK constraints outside of the table definition after all tables have been constructed.
ALTER TABLE `tbl`
ADD CONSTRAINT `constr`
FOREIGN KEY `fk_id` REFERENCES `ftbl`(`id`)
ON UPDATE CASCADE
ON DELETE CASCADE;
This way I can make sure the problem isn't something like the datatype of tbl.fk_id not being the same as the one of ftbl.id (including UNSIGNED as #Devart said). Or not having declared ftbl.id as unique. Regardless of the order of declaration of the tables.
After i do this i can integrate the constraint back into the table definition and take into account the order in which the tables need to be created to allow the constraint to be added.
You problem:
-- creating the sales table
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
-- creating the host_flags table
`sales_id` int(11) DEFAULT NULL,
-- the sales.id is declared as unsigned
-- the host_flags.sales_id is declared signed
Additonally to Recursed's answer:
There is a requirement that foreign keys contstraints' names must be unique in database scope. Maybe changing the name will work?
There is also a huge thread on MySQL community forums about the problem containing several solutions for some specific situations.
Possible two errors:
Reference and referenced columns must have the same type - int(11) unsigned
Unknown referenced table hosts.

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;