[英]Case when returning null row
以下是我的表格:
T1:
ID
1
2
3
T2:
ID (fk) value
1 Apple
1 Chocolate
2 Carrot
2 Chocolate
3 Candy
3 Chocolate
在我的查詢中:
select t1.id,
case when (t2.a) like 'app%'
then 'Apple'
end as 'Fruits',
case when (t2.a) like 'car%'
then 'Carrot'
end as 'Veggies'
from t1, t2
where t1.id = t2.id
這是我的輸出方式:
id Fruits Veggies
=====================
1 Apple
1
2 Carrot
2
3
我看到在輸出中,我得到了兩行,一行匹配 'fruit'/'veggie',另一行帶有null
。 為什么查詢也返回空行? 對不起,如果我的例子不是那么好。 基本上,我試圖用一些文本標識符再創建 2 列。
我期待這樣的輸出:
id Fruits Veggies
=====================
1 Apple
2 Carrot
3
編輯:我添加了上面的表結構並使用 from 和 where 子句更新了查詢。 在 where 子句中實現條件后,我意識到如果我在 where 子句中有上述條件,那么像 #3 這樣沒有 Apple 或 Carrot 的 ID 根本不會返回。
注意:我最初誤解了這個問題,並假設您希望嘗試替換提供結果的行中找到的值旁邊的空值。 這就是為什么我建議包括一個 ELSE。 我更改了示例以將過濾器包含在 WHERE 子句中,這樣您就不會得到既沒有 app% 也沒有 car% 的行。
例子:
select t1.id,
case when (t1.a) like 'app%' then 'Apple'
end as 'Fruits'
case when (t1.a) like 'car%' then 'Carrot'
end as 'Veggies'
where t1.a like 'app%' or t1.a like 'car%'
你得到了你不想要的結果行。 在您的WHERE
子句中排除它們:
where t1.a like 'app%' or t1.a like 'car%'
更新:您已更新您的問題,並希望顯示不在您的結果中的 ID 3。 你仍然沒有顯示你的 FROM 和 WHERE 子句。 如果您想顯示某行,但尚未顯示,那么要么您現有的 WHERE 子句限制性太強,要么您在需要外連接的地方使用內連接。
UPDATE2:既然您已經再次更新了您的請求,顯示了表結構和內容,它表明您實際上想要兩個查詢結果:apples 和carrots(這是一個非聚合查詢)加上每個 ID 的記錄,兩者都沒有也不是另一個(這是一個聚合;您查看所有 ID 的記錄以確定條件是否為真)。 您可以將這兩個查詢與UNION ALL
粘合在一起。
select
t2.id,
case when t2.a like 'App%' then 'Apple' end as "Fruits",
case when t2.a like 'Car%' then 'Carrot' end as "Veggies"
from t2
join t1 on t1.id = t2.id
where t2.a like 'App%' or t2.a like 'Car%'
union all
select id, null, null
from t2
group by id
having max(case when a like 'App%' or a like 'Car%' then 1 else 0 end) = 0;
評論:
like 'app%'
對你有用。 在我看來,它應該是t2.a like 'App%'
或lower(t2.a) like 'app%'
。鑒於您更新的信息,您需要左聯接而不是內聯接。
select t1.id,
case when (t2.a) like 'app%' then 'Apple' end as 'Fruits',
case when (t2.a) like 'car%' then 'Carrot' end as 'Veggies'
from t1 left join t2
on t1.id = t2.id
and (t2.a like 'app%' or t2.a like 'car%')
這將允許顯示所有 3 個 ID,但只為您提供右表上有蘋果或胡蘿卜的行,因為 where 條件已移至連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.