簡體   English   中英

返回空行時的情況

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

評論:

  • 此查詢中並不真正需要表 t1,但我猜它在您的真實查詢中,所以我保留了它。
  • 您的連接語法已過時二十多年,不應再使用。 我用適當的顯式連接替換了它。
  • 單引號用於字符串文字。 使用雙引號代替別名。
  • Oracle 通常區分大小寫。 我很驚訝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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM