0

我有以下两张表,一张存储订单信息,一张存储键|值信息。

没有CD = Dfor key COLOR_CD。我想加入两个表以获取所有订单,而不管表中未找到的键|值对MASS_DECODE

我可以得到一些帮助吗:D

订单信息

ORDER_NUMBER    |COLOR_CD   |
----------------|-----------|
1               |A          |
2               |B          |
3               |C          |
4               |D          |

MASS_DECODE

KEY         |CD             |VALUE      |
------------|---------------|-----------|
COLOR_CD    |A              |Green      |
COLOR_CD    |B              |Blue       |
COLOR_CD    |C              |Red        |
SIZE_CD     |A              |Large      |
SIZE_CD     |B              |Medium     |
SIZE_CD     |C              |Small      |

SQL:

select order_number, cd, value
from order_information
left outer join mass_decode 
on (color_cd = cd)
and key = 'COLOR_CD';

结果:

ORDER_NUMBER    |CD         |VALUE      |
----------------|-----------|-----------|
1               |A          |Green      |
2               |B          |Blue       |
3               |C          |Red        |

预期的:

ORDER_NUMBER    |CD         |VALUE      |
----------------|-----------|-----------|
1               |A          |Green      |
2               |B          |Blue       |
3               |C          |Red        |
4               |D          |NULL       |

编辑:对不起,我为我的表格提供了不正确的信息。自从得到纠正。

4

3 回答 3

1

您的列名不明确。您在两个表中有两个名称相同的列,那么 where 子句中的键指的是哪一列?我认为在更高版本的 Oracle 中,这实际上会给你一个错误。尝试这个:

select oi.order_number, oi.color_cd, md.value
from order_infomation oi
left outer join mass_decode md
on (oi.color_cd = md.cd)
where oi.key = 'KEY_A';

编辑:

根据您对@billy 的回复,这听起来对您不起作用。您还可以尝试将关键谓词放入连接子句中:

select oi.order_number, oi.color_cd, md.value
from order_infomation oi
left outer join mass_decode md
on (oi.color_cd = md.cd) and oi.key = 'KEY_A';
于 2012-09-26T02:38:18.227 回答
1
select *
  from order_information oi
   left join mass_decode md 
     on (
            oi.color_cd = md.cd 
        and oi.key = md.key
     )
where oi.key = 'KEY_A';

SQLFiddle

更新:

根据您的更新:

select *
  from order_information oi
   left join mass_decode md 
     on oi.color_cd = md.cd
where md.key = 'COLOR_CD' or md.key is null;

SQLFiddle

于 2012-09-26T02:45:43.387 回答
0

这应该这样做:

SELECT 
    order_number, 
    color_cd AS cd, 
    (
        SELECT value FROM mass_decode m2 WHERE m2.key = o.key AND m2.cd = o.color_cd
    ) AS value
FROM order_information o
WHERE o.key =  'KEY_A'
于 2012-09-26T02:50:46.550 回答