简体   繁体   English

从多个表引用一个外键

[英]Reference to one foreign key from multiple tables

I'm trying to connect one foreign key from multiple table's primary keys. 我正在尝试从多个表的主键连接一个外键。 Like this : 像这样 :

enter image description here 在此处输入图片说明

I've tried : 我试过了 :

ALTER TABLE Table1 ADD CONSTRAINT entity FOREIGN KEY (entity_id)
    REFERENCES MainTable(entitiy_id);

or 要么

ALTER TABLE MainTable 
    ADD FOREIGN KEY (entity_id) REFERENCES Table1(id),Table2(id),Table3(id); 

What should I do? 我该怎么办? Thanks. 谢谢。

it is not really clear what you want to achieve here. 目前尚不清楚您要在这里实现什么。 The foreign key should go from a non-key column of the "child" table to the key column of the referenced table. 外键应从“子”表的非键列转到引用表的键列。

In your diagram, I would expect each one of Table, Table2 and Table3 to have a column "parent_id", and in every one of them you add a foreign key, which goes from the "parent_id" column to the key of the MainTable. 在您的图表中,我希望Table,Table2和Table3的每一个都有一个“ parent_id”列,并在它们的每一个中添加一个外键,该外键从“ parent_id”列到MainTable的键。

That said, the code is 也就是说,代码是

ALTER TABLE Table1 ADD COLUMN parent_id INT NULL; ALTER TABLE Table1添加列parent_id INT NULL;

ALTER TABLE Table1 ADD CONSTRAINT fk_table1 FOREIGN KEY (parent_id) REFERENCES MainTable(uniqueId); ALTER TABLE Table1添加约束fk_table1外键(parent_id)参考MainTable(uniqueId);

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

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