如何在同一行中为相同的引用ID获取两个不同的值

时间:2019-04-04 09:38:04

标签: sql sql-server sql-server-2008

我有两个表: 1)产品 2)项目

产品表:

PId  Name   value1  value2
1    abc    1233    4567
2    xyz    9099    9099

项目表:

itemId  itemname  item_start   item_end
1        idc         1            2

item_start和item_end是产品表PId列上的引用。

现在,当我编写以下查询时:

select * from item left join product on item_start = PId and item_end = PId

然后它仅给出value1数据,但我想要类似这样的数据:

itemId  itemname  item_start  item_start_value1 item_start_value2  item_end    item_end_value1    item_end_value2
1        idc         1           1233               4567               2            9099            9099

我如何获得上述输出?

4 个答案:

答案 0 :(得分:1)

加入产品表两次。

SELECT item.*
     , productStart.Value1 AS product_start_value1
     , productStart.Value2 AS product_start_value2
     , productEnd.Value1 AS product_end_value1
     , productEnd.Value2 AS product_end_value2
  FROM item
  LEFT OUTER
  JOIN product productStart
    ON productStart.PId = item.item_start
  LEFT OUTER
  JOIN product productEnd
    ON productEnd.PId = item.item_end

答案 1 :(得分:0)

由于项目表上有2个FK,因此在产品表上需要2个联接。

SELECT I.itemId, I.itemname, I.item_start, P1.value1 as item_start_value1, P1.value2 as item_start_value2, I.item_end, P2.value1 as item_end_value1, P2.value2 as item_end_value2
FROM item 
LEFT JOIN product P1 ON item_start = PId 
LEFT JOIN product P2 ON item_end = PId

答案 2 :(得分:0)

可以做什么的示例:

select * from #Item i inner join #Product p on i.item_Start = p.Pid
inner join #Product p2 on i.Item_end = p2.PId

答案 3 :(得分:0)

SELECT item.itemId
     , item.itemname
     , item.item_start
     , productStart.Value1 AS item_start_value1
     , productStart.Value2 AS item_start_value2
     , item.item_end 
     , productEnd.Value1 AS item_end_value1
     , productEnd.Value2 AS item_end_value2
  FROM item
  Inner JOIN product productStart ON productStart.PId = item.item_start
  Inner JOIN product productEnd  ON productEnd.PId = item.item_end