MySQL ADD CONSTRAINT fail with [Err] 1215 - Cannot add foreign key constraint - mysql

I created two tables with the SQL:
CREATE TABLE `dinnertable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tableName` varchar(20) DEFAULT NULL,
`tableStatus` int(11) DEFAULT '0',
`orderDate` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `food` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`foodName` varchar(20) DEFAULT NULL,
`foodType_id` int(11) DEFAULT NULL,
`price` double DEFAULT NULL,
`mprice` double DEFAULT NULL,
`remark` varchar(200) DEFAULT NULL,
`img` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
);
But I can not ALTER the food TABLE to ADD CONSTRAINT:
ALTER TABLE food ADD CONSTRAINT fk_food_foodType_id FOREIGN KEY(foodType_id) REFERENCES foodType(id);
With the error info:
[SQL] ALTER TABLE food ADD CONSTRAINT fk_food_foodType_id FOREIGN KEY(foodType_id) REFERENCES foodType(id);
[Err] 1215 - Cannot add foreign key constraint

You're referring to the foodType table in your foreign key constraint definition. You should create that table before adding a constraint to it.
Moreover, that table should have field id as a primary key, matching the type of foodType_id.

Related

Why I am having a this error on phpmyadmin: Error creating foreign key on revision (check data types)?

I´m trying to create Foreign Keys in phpmyadmin, but I get this error:
Error creating foreign key on revision (check data types)
I don´t understand it because the data types are equal. So, what I want is to create a Foreign Key from 'acoustictreatment' to 'filterspecifications' which contains tag, offerid and revision. But I get the error that I mentioned.
This are my tables:
CREATE TABLE `offer` (
`projectid` varchar(20) NOT NULL,
`customer` varchar(255) NOT NULL,
`creator` varchar(255) NOT NULL,
`date` date NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `offer`
ADD PRIMARY KEY (`projectid`,`revision`);
CREATE TABLE `filterspecifications` (
`tag` varchar(100) NOT NULL,
`gasFlow` double NOT NULL,
`dustToHandle` double NOT NULL,
`offerid` varchar(20) NOT NULL,
`selectedFilter` varchar(20) NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `filterspecifications`
ADD PRIMARY KEY (`tag`,`offerid`,`revision`),
ADD KEY `offerid` (`offerid`,`revision`);
ALTER TABLE `filterspecifications`
ADD CONSTRAINT `filterspecifications_ibfk_1`
FOREIGN KEY (`offerid`,`revision`) REFERENCES `offer` (`projectid`, `revision`) ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TABLE `acoustictreatment` (
`tag` varchar(100) NOT NULL,
`offerid` varchar(20) NOT NULL,
`outputFanSilencer` tinyint(1) NOT NULL,
`fanAcousticInsulation` tinyint(1) NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `acoustictreatment`
ADD PRIMARY KEY (`tag`,`offerid`,`revision`);
The solution that I found is to delete the 'acoustictreatment' table and create it again with the foreign key from the beginning. Because what I was trying to do was to create all the tables and then create the foreign keys, but that didn´t work for me

Cannot add foreign key constraint in phpmyadmin - mysql

I have a table called teachers. I cannot use the id from teachers to create a composite table in slot table with the following query.
CREATE TABLE `teachers` (
`id` bigint(20) UNSIGNED NOT NULL,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE `teachers`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `teachers_email_unique` (`email`);
to create slot table
CREATE TABLE `slot` (
`teacher_id` bigint(20) NOT NULL,
`is_confirmed` tinyint(1) NOT NULL,
PRIMARY kEY (`teacher_id`),
foreign key (`teacher_id`) references `teachers`(`id`) on delete CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Data type of the referencing and referenced fields, should be exactly the same while defining a Foreign Key constraint. In your teachers table, id is BIGINT UNSIGNED, while in your slot table, it is BIGINT only. Add UNSIGNED clause as well:
CREATE TABLE `slot` (
`teacher_id` bigint(20) UNSIGNED NOT NULL,
`is_confirmed` tinyint(1) NOT NULL,
PRIMARY kEY (`teacher_id`),
foreign key (`teacher_id`) references `teachers`(`id`) on delete CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

How to fix 'MySQL Error: 1822. Missing index for contraint' On creating a composite foreign key

I'm trying to create a table with a composite foreign key, but keep getting met with the error Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'fk_contractdateshistoric_contractdates_multiple' in the referenced table 'contractdates'
I'm using MySQL v8.0.16
I've checked if the column types are different, and I'm not sure what else could be the problem.
Here are the tables that make up the problem, All tables are made happily but the last one that contains the composite key causes the problem.
CREATE TABLE `contracts` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) DEFAULT NULL,
`CreationDate` datetime DEFAULT NULL,
`CreatedBy` varchar(30) DEFAULT NULL,
`CompletionDate` date DEFAULT NULL,
`Comments` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE `fieldheading` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`fieldTypeID` int(11) DEFAULT NULL,
`fieldCode` int(11) DEFAULT NULL,
`fieldHeading` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE `contractdates` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DateValue` datetime DEFAULT NULL,
`ContractID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `uq_contractdates_contractID_FieldHeading_ID` (`ContractID`,`FieldHeadingID`),
KEY `fk_contractdates_contracts_id_idx` (`ContractID`),
KEY `fk_contractdates_fieldheading_id_idx` (`FieldHeadingID`),
CONSTRAINT `fk_contractdates_fieldheading_id` FOREIGN KEY (`FieldHeadingID`) REFERENCES `fieldheading` (`id`),
CONSTRAINT `fk_contractdates_contracts_id` FOREIGN KEY (`ContractID`) REFERENCES `contracts` (`id`)
) COMMENT='Table to hold the dates for a contract, one row is one date for a specific contract';
CREATE TABLE `contractdateshistoric` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ContractID` int(11) NOT NULL,
`ContractDateCurrentID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
`ChangedByID` int(11) NOT NULL,
`DateValue` datetime NOT NULL,
`TimeStampChanged` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx` (`ContractID`, `FieldHeadingID`, `ContractDateCurrentID`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple` FOREIGN KEY (`ContractID`, `FieldHeadingID`, `ContractDateCurrentID`) REFERENCES `contractdates` (`contractid`, `fieldheadingid`, `id`)
) COMMENT='Audit trail of the dates';
Since you are using Composite FK in the table contractdates try adding composite index as well
KEY `fk_contractdates_mutiple_idx` (`ContractID`,`FieldHeadingID`,`ID`)
Whole create statement
CREATE TABLE `contractdates` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DateValue` datetime DEFAULT NULL,
`ContractID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `fk_contractdates_contracts_id_idx` (`ContractID`),
KEY `fk_contractdates_fieldheading_id_idx` (`FieldHeadingID`),
KEY `fk_contractdates_mutiple_idx` (`ContractID`,`FieldHeadingID`,`ID`),
CONSTRAINT `fk_contractdates_fieldheading_id` FOREIGN KEY (`FieldHeadingID`) REFERENCES `fieldheading` (`id`),
CONSTRAINT `fk_contractdates_contracts_id` FOREIGN KEY (`ContractID`) REFERENCES `contracts` (`id`)
) COMMENT='Table to hold the dates for a contract, one row is one date for a specific contract';
It's trying to tell you "you haven't created a necessary unique index on contractdates, that covers the columns (contractid, fieldheadingid, id) so I cannot create a foreign key on contractdateshistoric that refers to this set of columns when determining the single parent row"
I'm not sure why you're creating an fk that references 3 columns when contractdates has a pk that is just the ID column.
If a contractdateshistoric records refers to a single contractdates record as its parent, the historic record should have a contractdateid column that refers to contractdates.id - no need for multiple columns. Copy the pattern you used to relate a contractdates to its parent contract, and you'll be fine
I have tried by creating the keys individually for the columns, Please find the updated query:
CREATE TABLE `contractdateshistoric` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`ContractID` INT(11) NOT NULL,
`ContractDateCurrentID` INT(11) NOT NULL,
`FieldHeadingID` INT(11) NOT NULL,
`ChangedByID` INT(11) NOT NULL,
`DateValue` DATETIME NOT NULL,
`TimeStampChanged` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx` (`ContractID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx1` (`FieldHeadingID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx2` (`ContractDateCurrentID`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple` FOREIGN KEY (`ContractID`)
REFERENCES `contractdates` (`contractid`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple1` FOREIGN KEY (`FieldHeadingID`)
REFERENCES `contractdates` (`fieldheadingid`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple2` FOREIGN KEY (`ContractDateCurrentID`)
REFERENCES `contractdates` (`id`)
);
It works fine.

#1215 - Cannot add foreign key constraint

I have this weird issue with creation of foreign key.
Given 2 tables:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) NOT NULL,
`merchant_id` int(11) NOT NULL,
`minimum_qty` int(11) NOT NULL,
`maximum_qty` int(11) NOT NULL,
`target_met_email` int(11) NOT NULL,
`coupon_barcode` text NOT NULL,
`coupon_merchant_address` int(11) NOT NULL,
`coupon_merchant_contact` int(11) NOT NULL,
`coupon_expiration_date` date DEFAULT NULL,
`coupon_price` int(11) NOT NULL,
`coupon_fine_print` int(11) NOT NULL,
`coupon_highlights` int(11) NOT NULL,
`coupon_merchant_description` int(11) NOT NULL,
`coupon_business_hours` int(11) NOT NULL,
`coupon_merchant_logo` int(11) NOT NULL,
`coupon_additional_info` text NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
`coupon_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`groupdeals_id` int(11) NOT NULL,
`order_item_id` int(11) NOT NULL,
`coupon_code` varchar(255) NOT NULL DEFAULT '',
`redeem` varchar(255) NOT NULL DEFAULT '',
`status` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`coupon_id`),
KEY `fk_groupdeals_coupons_groupdeals1_idx` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I try to add foreign key by executing following query:
ALTER TABLE `groupdeals_coupons`
ADD CONSTRAINT `fk_groupdeals_coupons_groupdeals1`
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
All I receive is Error:
#1215 - Cannot add foreign key constraint
Show engine innodb status
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2013-08-17 13:47:49 7ff5dbb2c700 Error in foreign key constraint of table xxxxx/#sql-7b23_282b1a:
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
The column groupdeals.groupdeals_id is a primary one, so I really can't understand where is a problem :|
Any hints?
Server type: Percona Server
Server version: 5.6.11-rc60.3-log - Percona Server (GPL), Release 60.3
Your types are inconsistent:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
[...]
`groupdeals_id` int(11) NOT NULL,
As you will see, in one table you have int unsigned. In the other, just int.
BTW, I noticed you have two keys on groupdeals_id. Is that on purpose?
CREATE TABLE IF NOT EXISTS `groupdeals` (
[...]
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
Try these two steps to add foreign key:-
alter table groupdeals_coupons modify groupdeals_id int unsigned not null default 0;
ALTER TABLE groupdeals_coupons ADD CONSTRAINT fk_groupdeals_coupons_groupdeals1 FOREIGN KEY (groupdeals_id) references groupdeals (roupdeals_id);

It it possible to add a foreign key constraint to a composite key in mysql?

So I have 2 tables.
subject_schedule:
CREATE TABLE IF NOT EXISTS `subject_schedule` (
`subject` varchar(10) NOT NULL,
`schedule_id` int(11) NOT NULL,
`id` int(11) NOT NULL,
PRIMARY KEY (`subject`,`schedule_id`),
KEY `schedule_id` (`schedule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and appointment:
CREATE TABLE IF NOT EXISTS `appointment` (
`work_plan` varchar(1000) DEFAULT NULL,
`date` date DEFAULT NULL,
`homework_given` varchar(1000) DEFAULT NULL,
`tutor_comments` varchar(1000) DEFAULT NULL,
`admin_comments` varchar(1000) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`schedule_id` int(11) NOT NULL,
`attended` tinyint(1) NOT NULL DEFAULT '1',
`arrival_time` time DEFAULT NULL,
`departure_time` time DEFAULT NULL,
`homework_completed` tinyint(1) NOT NULL DEFAULT '0',
`subject` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `schedule_id` (`schedule_id`),
KEY `subject` (`subject`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10004 ;
I want to create a foreign key which references the composite key in appointment. I have tried:
ALTER TABLE 'appointment'
ADD CONSTRAINT 'appointment_fk' FOREIGN KEY (`schedule_id`, `subject`)
REFERENCES 'subject_schedule' ('schedule_id', 'subject');
but it returns an error in PhpMyAdmin:
#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 ''appointment' ADD CONSTRAINT 'appointment_fk' FOREIGN KEY
(schedule_id, `su' at line 1
What am I doing wrong?
Is it better to just have an id as a primary key and reference that instead of using a composite key?
the columnNames shouldn't be wrap with single quotes because it will be converted to a string (not a column anymore)
ALTER TABLE appointment
ADD CONSTRAINT appointment_fk FOREIGN KEY (`schedule_id`, `subject`)
REFERENCES subject_schedule (schedule_id, subject);
SQLFiddle Demo