简体   繁体   中英

MySQL problem to add FOREIGN KEY?

I've got 2 innodb tables, here it is with SHOW CREATE TABLE query:

| top_menu | CREATE TABLE `top_menu` (
  `t_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `menu_photo` char(128) NOT NULL,
  `title` char(64) NOT NULL,
  `atdc_id` int(10) unsigned NOT NULL,
  `menu_order` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 |

| attendance | CREATE TABLE `attendance` (
  `atdc_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` char(128) NOT NULL,
  `content` text,
  `price` double NOT NULL,
  `sale_percent` tinyint(3) unsigned NOT NULL,
  `atdc_order` int(10) unsigned NOT NULL,
  `s_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`atdc_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |

The result of doing, normal adding FOREIGN KEY is an error. Query: ALTER TABLE top_menu ADD FOREIGN KEY (atdc_id) REFERENCES attendance(atdc_id); Error: ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ( database ., CONSTRAINT #sql-a36a_5c109d2_ibfk_1 FOREIGN KEY ( atdc_id ) REFERENCES attendance ( atdc_id ))

What should I do with this? It always worked for me well.

It seems that some top_menu rows have the atdc_id which does not exist in attendance table.

in complement to @Alexey Smirnoff answer: When are you adding the foreign key? If it is from a restore script ensure you have the attendance table content loaded before you perform this query. Or delay foreign key checks to the end of the process.

If you want to find which rows are giving you this problem run this query:

Select a.* 
from top_menu a
left join attendance b
on a.atdc_id = b.atdc_id
where b.atdc_id IS NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM