没有行时选择CASE / JOIN

时间:2011-07-16 22:01:13

标签: sql join db2 select-case

对不起,这个有点头疼。我将从示例开始:

表:

TownCountry

Record |  Town  | CountryCode
-------+--------+-------------
1      | London | A1
2      | Cardiff| A2
3      | Hull   | A1
4      | Luton  | A1

ReFData

Type    |  Code   | Country
--------+---------+-------------
Country | A1      | England
Country | A2      | Wales

如果我的查询是:

select a.Town, b.Country from TownCountry a, RefData b, TownCountry c
where a.Record=1
and b.Code=c.CountryCode and c.Record=2

我明白了:

London | Wales

但是,如果我将Wales的代码更改为A3,并保持查询相同,则结果不会返回任何行。

我想要的是,在威尔士是A3的例子中,我的结果是:

London | (empty)

我尝试过COALESCE:

select a.Town, COALESCE(b.Country,'empty') from TownCountry a, RefData b, TownCountry c
where a.Record=1
and b.Code=c.CountryCode and c.Record=2

但这没有返回任何行

我也尝试过选择大小写,左右连接,但仍然没有行。

以下是我的好朋友在讨论时给我的一个更简单的例子:

城镇

Record |  Town  
-------+--------
1      | London 
2      | Cardiff
4      | Luton

select a.Town, b.Town, c.town, d.Town
from Towns a, Towns b, Towns c, Towns d
where a.Reocrd=1 and b.Reocrd=2 and c.Reocrd=3 and a.Reocrd=4

我想返回

a.Town | b.Town | c.Town | d.Town
-------+--------+--------+--------
London | Cardiff| NULL   | Luton

任何帮助都非常感激。

3 个答案:

答案 0 :(得分:0)

如果您希望将行保留在您加入的列上没有匹配的位置,则需要执行OUTER JOIN而不是INNER JOIN

http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=/com.ibm.db2.luw.apdv.porting.doc/doc/r0052878.html

答案 1 :(得分:0)

你不是真的做连接,你需要一个外连接(即LEFT JOIN)。

你想要的是这样的:

select a.Town, b.Country
from TownCountry a
left join RefData b on b.Code = a.CountryCode
left join TownCountry c on c.CountryCode = b.Code and c.Record=2
where a.Record=1;

已编辑:我将“和c.Record = 2”放入join子句中。这个小技巧很好 - 它保留了条件,但不需要连接行

答案 2 :(得分:0)

这里的问题是Translation表没有空白原始值的条目。 因此,Translation表中没有任何内容匹配,因此不返回任何行。

这个特殊问题可以通过在Translation表中添加一行来解决,或者更准确地说,使用union来添加行:

select a.Town, b.Country from TownCountry a, 
(select Code, Country from RefData b
union select '' as Code, 'Not found' as Country from RefData c), TownCountry c
where a.Record=1
and b.Code=c.CountryCode and c.Record=2

SQL Love, 翼

相关问题