2

抱歉,这个有点头疼。我将从示例开始:

表:

城镇国家

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

参考数据

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

但是,如果我将威尔士的代码更改为 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

非常感谢任何帮助。

4

3 回答 3

0

如果您想保留行,即使您要加入的列上没有匹配项,您需要执行 anOUTER JOIN而不是INNER JOIN.

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

于 2011-07-16T22:14:31.607 回答
0

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

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

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 爱,翼

于 2011-07-17T17:23:09.947 回答
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;

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

于 2011-07-16T23:05:03.523 回答