[英]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.