左连接多个结果

时间:2016-09-03 05:50:49

标签: sql oracle join left-join

我有一个像这样的查询:

Select i.*, prop1.VALUE as PROPERTY_ONE, prop2.VALUE as PROPERTY_TWO
From ITEM i
    Left Join ITEM_PROPERTY prop1 on i.ITEM_ID = prop1.ITEM_D and prop1.PROPERTY_ID = 1 
    Left Join ITEM_PROPERTY prop2 on i.ITEM_ID = prop2.ITEM_D and prop2.PROPERTY_ID = 2

有没有办法只使用1个左连接并获取所有属性?

4 个答案:

答案 0 :(得分:1)

如果我的理解是正确的,那么您可以通过以下方式获得所需的结果:

SELECT i.*, 
    CASE WHEN prop1.PROPERTY_ID = 1 THEN prop1.VALUE ELSE '' END AS  PROPERTY_ONE, 
    CASE WHEN prop1.PROPERTY_ID = 2 THEN prop1.VALUE ELSE '' END AS  PROPERTY_TWO
FROM ITEM i
LEFT JOIN ITEM_PROPERTY prop1 on i.ITEM_ID = prop1.ITEM_D 
AND prop1.PROPERTY_ID IN (1, 2)

答案 1 :(得分:0)

Select i.*, GROUP_CONCAT(prop.VALUE) as PROPERTY_VALUE
From ITEM i
Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D 

答案 2 :(得分:0)

旧式:

"[itemId=TestCheckbox]": {
   change: this.updateCheckbox
}

或(“轻”版本,少了gorup中的列表。但是优化可能存在问题):

Select i.*,
       max(decode(prop.PROPERTY_ID,1,prop.VALUE,NULL)) as PROPERTY_ONE,
       max(decode(prop.PROPERTY_ID,2,prop.VALUE,NULL)) as PROPERTY_TWO
  From ITEM i
  Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D and prop.PROPERTY_ID in(1,2)
 group by there_will_have_to_list_all_the_fields_from_ITEM

新样式(Oracle 11g +):

Select i.*,prop.PROPERTY_ONE,prop.PROPERTY_TWO
  From ITEM i
  Left Join (
    select ITEM_ID,
           max(decode(PROPERTY_ID,1,VALUE,NULL)) as PROPERTY_ONE,
           max(decode(PROPERTY_ID,2,VALUE,NULL)) as PROPERTY_TWO
      from ITEM_PROPERTY
     where PROPERTY_ID in(1,2)
     group by ITEM_ID
  ) prop on i.ITEM_ID = prop.ITEM_D

答案 3 :(得分:0)

 Select i.*, prop1.VALUE as PROPERTY_ONE, prop2.VALUE as PROPERTY_TWO
    From ITEM i
    Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D and prop.PROPERTY_ID in (1,2)