使用配对 ID table 左加入行

Left Join row using pairing id table

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

我的结构是这样的:

项Table

itemID    attribute1     attribute2

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

项目对 Table

itemPairID   firstItemID   secondItemID

1            2              4
2            1              3

我想做的是从 items table 执行 select ,同时从 items table 左侧加入成对的行为了也从该配对项中获取属性。

据我所知:

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'

如果您试图显示其他链接项的属性,则只需使用 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

您需要双连接:

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

试试这个:

SELECT ip.itemPairID         AS ip_itemPairID, 
       ip.firstItemID        AS ip_firstItemID, 
       ip.secondItemID       AS ip_secondItemID, 
       firstItem.attribute1  AS firstItem_attribute1, 
       firstItem.attribute2  AS firstItem_attribute2, 
       secondItem.attribute1 AS secondItem_attribute1, 
       secondItem.attribute2 AS secondItem_attribute2 
FROM   ItemPairs ip 
       INNER JOIN Items firstItem 
               ON firstItem.itemID = ip.firstItemID 
       INNER JOIN Items secondItem 
               ON secondItem.itemID = ip.secondItemID 
WHERE  ip.firstItemID = 1 
        OR ip.secondItemID = 1