[英]Can two columns from one table have a foreign key to the same column in another table?
I have two tables in a database, Person and Pet. 我的数据库中有两个表Person和Pet。
CREATE TABLE Person (
id INT NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner)
REFERENCES Person(id),
FOREIGN KEY (current_owner)
REFERENCES Person(id)
)
I am trying to reference the previous owner, and the current owner for each pet. 我试图参考每只宠物的前主人和当前主人。 I have also tried
我也尝试过
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner, current_owner)
REFERENCES Person(id, id)
)
and 和
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner, current_owner)
REFERENCES Person(id)
)
but I get the following error: 但我收到以下错误:
Error Code: 1215. Cannot add foreign key constraint
错误代码:1215。无法添加外键约束
Is this even possible to accomplish? 这有可能实现吗? Or would I have to create some sort of bridge table to accommodate this?
还是我必须创建某种桥接表来解决此问题?
Please try the following: 请尝试以下操作:
CREATE TABLE IF NOT EXISTS `pet` (
`id` int(11) NOT NULL,
`original_owner` int(11) NOT NULL,
`current_owner` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `origin` (`original_owner`),
KEY `current` (`current_owner`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `pet`
ADD CONSTRAINT `pet_ibfk_2` FOREIGN KEY (`current_owner`) REFERENCES `person` (`id`),
ADD CONSTRAINT `pet_ibfk_1` FOREIGN KEY (`original_owner`) REFERENCES `person` (`id`);
The problem was the order I had the tables defined in the script. 问题是我在脚本中定义了表的顺序。 I had Pet come before Person.
我让宠物先于人。 Once I put Person above Pet it worked fine.
一旦我将“人”放在“宠物”之上,它就可以正常工作。 The example in the question was written from my head, as I didn't have the actual code handy when I posted it.
问题中的示例是从我的头上写的,因为发布时我没有实际的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.