[英]SELECT CASE/JOIN when no rows
抱歉,这个有点头疼。 我将从示例开始:
表:
城镇国家
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
但这没有返回任何行
我也试过 select 案例,左右连接,但仍然没有行。
这是我的好朋友在讨论时给我的一个更简单的例子:
城市
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
非常感谢任何帮助。
如果您想保留行,即使您要加入的列上没有匹配项,您需要执行OUTER JOIN
而不是INNER JOIN
。
你并不是真的在做连接,你需要一个外连接(即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”放入连接子句中。 这个小技巧很好——它保留了条件,但不需要连接行
这里的问题是 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 爱,翼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.