[英]Foreign Key From two tables in one column in SQL
I have a order
table and each order in that table belongs to either a device
or part
(these two have no specific intersection in fields). 我有一个order
表,该表中的每个订单都属于一个device
或一个part
(这两个在字段中没有特定的交集)。
So I need to store the did
or pid
as FK in order
table. 所以我需要在order
表中将did
或pid
存储为FK。
"device"
+----+....
| id |<---------+
+----+.... :
: : : : . :
:
:
"part" :
+----+.... :
| id |<-------+ :
+----+.... : :
: : : : . : :
: :
: :
"order" @ @
+-----+-------+....
| id | for |....
+-----+-------+....
: : : : : : : : .
Now How should I do this? 现在我该怎么做?
type
field to order
table and store both pid
or did
on one column(eg for
) 将一个type
字段添加到order
表并将pid
或did
存储在一列上(例如for
) type
, pid
, did
columns 使用type
, pid
, did
列创建中间视图 goods
) and make its PK to be FK on order
, part
, device
创建更高级别的表(例如goods
)并使其PK在order
, part
, device
上为FK Which one is the best method? 哪一个是最好的方法? or some other method? 还是其他一些方法?
Either use exclusive foreign keys or inheritance , as explained here . 要么使用独家的外键或继承 ,如解释在这里 。 Just be careful about CHECK, which is not enforced by MySQL, so you'll have to "emulate" it via trigger. 请注意CHECK 没有强制执行 ,因此你必须通过触发器“模拟”它。
Please don't do the "type" approach, it can lead to problems . 请不要做“类型”的方法,它可能会导致问题 。
I would go with two tables, one for the order and the other for item. 我会选择两个表,一个用于订单,另一个用于商品。 Item table will have ID, type (part or device; P or D) and the rest of the details. 物料表将具有ID,类型(部件或设备; P或D)以及其余详细信息。 In the order table, I will just have a FK to the Item Table ID. 在订单表中,我将只有一个FK到项目表ID。
If it was me, I would create both the following FK fields: did
and pid
. 如果是我,我会创建以下FK字段: did
和pid
。 You would always have a value for one and not the other. 你总是有一个值,而不是另一个。
Your query would look something like the following: 您的查询将如下所示:
SELECT o.*, COALESCE(p.descr, d.descr) AS Description,
COALESCE(p.number, d.number) AS PNumber
FROM order o
LEFT JOIN device d ON o.did = d.id
LEFT JOIN part p ON o.pid = p.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.