[英]SQL Server : multiple foreign keys from first table linking to the primary key of second table
I have two tables, itemrequest_table
and item_table
. 我有两个表,
itemrequest_table
和item_table
。 Four columns of itemrequest_table
( item1, item2, item3, item4
) are connected to item_no
of item_table
. itemrequest_table
四列( item1, item2, item3, item4
)连接到item_no
的item_table
。
I'm trying to write a query to display the item names of item_nos under the column of item1, item2, item3, item4. 我正在尝试编写查询以在item1,ite2,ite3,item4列下显示item_nos的项目名称。
But how can I display the item names it? 但是如何显示项目名称呢? And is it possible to query that?
可以查询吗?
My tables: 我的桌子:
You just need to do four joins between the two tables - one for each item: 您只需要在两个表之间进行四个联接-每个项一个:
SELECT
Item1 = i1.item_name,
Item2 = i2.item_name,
Item3 = i3.item_name,
Item4 = i4.item_name
FROM
itemrequest_table ir
INNER JOIN
item_table i1 ON ir.item1 = i1.item_no
INNER JOIN
item_table i2 ON ir.item2 = i2.item_no
INNER JOI
item_table i3 ON ir.item3 = i3.item_no
INNER JOIN
item_table i4 ON ir.item4 = i4.item_no
But this is really a bad design - it smells of first-normal form violation ( repeating columns ). 但这确实是一个糟糕的设计-闻到第一范式违规( 重复列 )的味道。 What you really should do is just have a relationship between
itemrequest_table
and the item_table
that allows for any number of connections, if needed (a regular, normal m:n relationship) 您真正应该做的就是在
itemrequest_table
和item_table
之间itemrequest_table
一个关系,该关系允许任意数量的连接(如果需要的话)(常规的正常m:n关系)
You need to perform four joins: 您需要执行四个联接:
SELECT ir.request_no,
t1.item_name, t2.item_name, t3.item_name, t4.item_name
FROM itemrequest_table ir
LEFT JOIN item_table t1 ON ir.item1 = t1.item_no
LEFT JOIN item_table t2 ON ir.item2 = t2.item_no
LEFT JOIN item_table t3 ON ir.item3 = t3.item_no
LEFT JOIN item_table t4 ON ir.item4 = t4.item_no
EDIT: 编辑:
As per the comments, these items are optional, so a left join
should be used instead of a join
. 根据注释,这些项目是可选的,因此应使用
left join
代替join
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.