[英]One foreign key references multiple primary keys
I have two tables with single primary key columns in each of those two tables and another table (table 3) which has a foreign key that refers both of those above primary key's columns. 我有两个表,在这两个表中的每个表中都有一个主键列,而另一个表(表3)中有一个外键,该外键引用了那些在主键列上方的表。
Now I want to insert records into table 3 if it present in either of those two primary key tables. 现在,我想将记录插入到表3中(如果这两个主键表中的任何一个存在)。
Note : I don't want to create a new table that is combination of primary key tables and add reference to that newly created table 注意 :我不想创建一个由主键表组成的新表,并添加对该新创建表的引用
As Erwin Brandstetter stated here 正如Erwin Brandstetter 在这里所述
To answer the question in the title and at the end of your text: 要在标题和文本结尾处回答问题:
"I would still like to know how to have one foreign key referencing two primary keys." “我仍然想知道如何使用一个外键引用两个主键。”
That's impossible. 这不可能。
A FOREIGN KEY
constraint can only point to one table and each table can only have one PRIMARY KEY
constraint. 一个
FOREIGN KEY
约束只能指向一个表,而每个表只能有一个 PRIMARY KEY
约束。
Or you can have multiple FOREIGN KEY
constraints on the same column(s) referencing one PRIMARY KEY
of a (different) table each. 或者,您可以在同一列上具有多个
FOREIGN KEY
约束,分别引用一个 (不同)表的一个 PRIMARY KEY
。 (Rarely useful.) (非常有用。)
However , a single PK or FK can span multiple columns. 但是 ,单个PK或FK 可以跨越多列。
And a FK can reference any explicitly defined unique (set of) column(s) in the target, not just the PK. FK可以引用目标中任何显式定义的唯一(一组)列,而不仅仅是PK。 The manual:
手册:
A foreign key must reference columns that either are a primary key or form a unique constraint.
外键必须引用作为主键或形成唯一约束的列。
A multicolumn PK or UNIQUE
constraint can only be referenced by a multicolumn FK constraint with matching column types. 多列PK或
UNIQUE
约束只能由具有匹配列类型的多列FK约束引用。
Basic advice: 基本建议:
insert into table3 (col1, col2 ...)
(select col1, col2 ... from table1
union
select col1, col2 ... from table2);
You can optionally put where clauses or split the SQL into 2, instead of a union. 您可以选择放置where子句或将SQL拆分为2,而不是并集。
This is standard ANSI SQL and should work on any DBMS 这是标准的ANSI SQL,适用于任何DBMS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.