简体   繁体   English

添加外键时出错

[英]error in adding foreign key

I have two tables: tab1,tab2 我有两个表: tab1,tab2

I want add a foreign key to tab2 and wrote this query 我想向tab2添加外键并编写此查询

ALTER TABLE tab2
ADD FOREIGN KEY(name) REFERENCES tab1(name)

But I get this error: 但是我得到这个错误:

error 1005(HY000):can't create table 'club.#sql-6f0_2' (errno:150)

What is wrong? 怎么了?

Edit

i write this tables only for test.

tab1

name char(20) private key

lname char(20)


tab2

ssn int private key

name char(20)

I answered this for you about an hour ago in a comment on your other question, but here it is again: 大约一个小时前,我在对您的另一个问题的评论中为您回答了这个问题,但这里又是一个问题:

You can get details on that error by running SHOW ENGINE INNODB STATUS\\G and reading the LATEST FOREIGN KEY ERROR section. 您可以通过运行SHOW ENGINE INNODB STATUS\\G并阅读“ LATEST FOREIGN KEY ERROR部分来获取有关该错误的详细信息。

The most likely reasons for this failure: 失败的最可能原因:

  • tab1.name and tab2.name are not exactly the same data type tab1.name和tab2.name数据类型不完全相同
  • tab1.name is not unique tab1.name不是唯一的

try this: 尝试这个:

alter table tab2
add foreign key my_key(name) references tab1(name)

maybe Your key should have a name? 也许您的钥匙应该有名字?

您不能在默认的MySQL存储引擎(ISAM,MyISAM)上定义外键,使用InnoDB作为引擎,然后添加外键约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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