How to add foreign key to MySQL table?

北城以北 提交于 2019-12-25 07:29:37

问题


I use MySQL with InnoDB engine. I double-checked type of columns. But always have:

Error Code: 1215. Cannot add foreign key constraint

I tried:

ALTER TABLE `mail`.`boxes`  
    ADD CONSTRAINT FK_id 
    FOREIGN KEY (id) 
    REFERENCES `mail`.`users` (id)
    ON UPDATE NO ACTION 
    ON DELETE NO ACTION; 

and

ALTER TABLE `mail`.`boxes` 
  ADD FOREIGN KEY (id)
  REFERENCES `mail`.`users` (id)

Nothing works(((

Please, help, what I am doing wrong (except choosing MySQL :-) )?


回答1:


If table contains data then you are not able to add foreign key you drop table object and recreate use below reference for the same

Basics of Foreign Keys in MySQL?




回答2:


To check what exactly the problem is, use:

SHOW ENGINE INNODB STATUS\G

There is section "last foreign key error". Look at: http://dev.mysql.com/doc/refman/5.0/en/innodb-monitors.html

My guess is that data type od mail.boxes (id) and mail.users (id) is not the same. (E.g. smallint in one table and integer in second one).

Data in table on which you're trying to create FK could possibly also be problem (are your mailbox ids the same as id of existing users?)



来源:https://stackoverflow.com/questions/17613758/how-to-add-foreign-key-to-mysql-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!