在多列上添加外键
我正在尝试在表的两列上创建外键以指向另一个表的同一列,但我似乎收到错误...
这就是我所做的:
CREATE TABLE test2 (
ID INT NOT NULL AUTO_INCREMENT,
col1 INT NOT NULL,
col2 INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk FOREIGN KEY (col1, col2)
REFERENCES test1(ID, ID)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB;
但我收到
错误 1005 (HY000 ): 无法创建表 'DB.test2' (errno: 150)
但是,如果我只有一列,则表会正确创建。
有人可以向我指出错误在哪里吗?
谢谢 n
I'm trying to create a foreign key on two columns of a table to point to the same column of another table, but I seem to get an error...
Here's what I do:
CREATE TABLE test2 (
ID INT NOT NULL AUTO_INCREMENT,
col1 INT NOT NULL,
col2 INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk FOREIGN KEY (col1, col2)
REFERENCES test1(ID, ID)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB;
But I get
ERROR 1005 (HY000): Can't create table 'DB.test2' (errno: 150)
If I only have one column, however, the table is correctly created.
Could someone point out to me where the error is?
Thanks
n
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这里尝试了一下,得到了同样的错误。但这是有效的:
是的,我知道 - 你的脚本应该工作(即使它看起来没有多大意义)。然而,我认为这个新版本更好。
Tried it here and got the same error. This works though:
Yes, I know - your script should work (even if it doesn't seem to make much sense). Yet, I guess this new version is better.
问题似乎是您在同一个外键(即(ID,ID))中两次指定相同的父列。以下应该可行:
如果是这种情况,您希望子表中的两列引用相同的父表列,那么您必须添加两个外键引用,如 rsenna 所示,因为它们代表两个独立关系。
The problem would appear to be that you are specifying the same parent column twice in the same foreign key (i.e, (ID, ID)). The following should work:
If it is the case, that you want two columns in a child table referencing the same parent table column, then you must add two foreign key references as shown by rsenna as those represent two independent relations.