使用配对ID表

时间:2019-02-20 22:37:32

标签: sql sql-server tsql sql-server-2014

我正在使用MS SQL Server 2014,并尝试执行困难的左联接操作。

我的结构如下:

项目表

itemID    attribute1     attribute2

1         blue           small
2         green          large
3         brown          medium
4         yellow         extra small
5         orange         extra large

ItemPairs表

itemPairID   firstItemID   secondItemID

1            2              4
2            1              3

我要执行的操作是从items表中进行选择,同时保留items表中的配对行,以便也从该配对项中获取属性。

据我所知:

SELECT attribute1, attribute2, ip.firstitemid, ip.seconditemid
FROM items
LEFT JOIN
    itempairs ip on items.itemid = ip.firstitemid or items.itemid = ip.seconditemid
WHERE itemid = '1'

3 个答案:

答案 0 :(得分:1)

您需要双重加入:

select i1.*, i2.*
from itempairs ip 
inner join items i1 on i1.itemid = ip.firstitemid
inner join items i2 on i2.itemid = ip.seconditemid

如果您还需要未配对的物品:

select i1.*, i2.*
from itempairs ip 
inner join items i1 on i1.itemid = ip.firstitemid
inner join items i2 on i2.itemid = ip.seconditemid
union
select i.*, null, null, null
from items i
where i.itemid not in (
  select firstitemid from itempairs
  union
  select seconditemid from itempairs
)

如果您只想要特定的一对,

select i1.*, i2.*
from itempairs ip 
inner join items i1 on i1.itemid = ip.firstitemid
inner join items i2 on i2.itemid = ip.seconditemid
where (i1.itemid = 1) or (i2.itemid = 1)

请参见demo

答案 1 :(得分:0)

如果要显示其他链接项的属性,则只需使用CASE WHEN子句和WHERE IN子句:

SELECT * FROM items WHERE Itemid IN (

SELECT DISTINCT CASE WHEN ip.firstitemid = items.itemid THEN ip.seconditemid ELSE ip.firstitemid END as otherItem
FROM items
LEFT JOIN
    itempairs ip on items.itemid = ip.firstitemid or items.itemid = ip.seconditemid
WHERE itemid = '1' )

或使用带有子查询的INNER JOIN:

SELECT * FROM  items T1 INNER JOIN (

SELECT DISTINCT CASE WHEN ip.firstitemid = items.itemid THEN ip.seconditemid ELSE ip.firstitemid END as otherItem
FROM items
LEFT JOIN
    itempairs ip on items.itemid = ip.firstitemid or items.itemid = ip.seconditemid
WHERE itemid = '1' ) as T2 INNER JOIN  ON T2.otherItem = T1.ItemID

答案 2 :(得分:0)

尝试一下:

C