[英]SQL return a default value if a row is not found [PostgreSQL]
我想知道是否可行(如果可能,在一個查詢中)如果缺少行,則查詢返回默認值? 例如,取這兩個表並給出我的查詢需要2個參數(place_id和user_id)
T1
place_id / tag_id
1 2
1 3
1 4
2 4
3 2
4 5
T2
user_id / tag_id / count
100 2 1
100 3 20
200 4 30
200 2 2
300 5 22
如您所見,缺少對用戶/標簽(100,4)。 我想歸檔的是一個查詢,它將返回這3個結果
tag_id / count
2 1
3 20
4 0
我知道我可以用這樣的東西做到這一點,但它與最終結果並不匹配,因為只有事先知道tag_id ...並且顯然只返回1行..它才有效。
SELECT T1.tag_id, T2.count
from T1 t1
left join T2 t2 on t1.tagId=t2.tag_id
where t1.place_id=1
UNION ALL
select tag_id,0
from T1
where not exist (select 1 from T2 where user_id=100 and tag_id=4)
and tag_id=4;
編輯:我的問題不完整,這里有遺漏的案例就是一個例子(cuaesy of @a_horse_with_no_name) http://sqlfiddle.com/#!12/67042/4
謝謝!
外連接已經處理了你想要的東西。
由於t1
是連接的“左表”,因此將返回t1
所有行。 “右表”(在您的示例中為t2
)中的列將具有null
值。 所以你只需要將null
轉換為0
:
select t1.tag_id, coalesce(t2.cnt, 0)
from T1 t1
left join T2 t2 on t1.tag_Id=t2.tag_id
and t1.place_id = 1;
SQLFiddle示例: http ://sqlfiddle.com/#!12/ed7bf/1
不相關但是:
使用count
作為列名是一個非常糟糕的主意,因為它需要您始終用雙引號括起列名: t2."count"
因為它是一個保留字。 另外,它並沒有真正記錄專欄的用途。 你應該找到一個更好的名字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.