鑒于這兩個表
A B
id id a_id
---- ---------
1 1 1
2 2 1
3 3 2
4 2
5 2
6 3
7 NULL
8 NULL
我需要從回傳所有的IDB以及每個ID的回報,如果有一個以上的參考A。IE
result
B.id more_than_one_reference
-----------------------------
1 true
2 true
3 true
4 true
5 true
6 false
7 false
8 false
因為B.id = 1,2我需要回傳,true因為Bwith 中有兩行a_id = 1。
因為B.id = 3,4,5我需要回傳,true因為Bwith 中有三行a_id = 2。
對于B.id = 6我需要回傳false,因為有一排B用a_id = 3。
因為B.id = 7,8我需要回傳,false因為相應的a_id值是NULL.
我可以看到,就我的目的而言,簡單COUNT(B.id) > 1檢查(對于給定的 a_id)就足夠了,但我無法將此結果加入SELECT B.id FROM B查詢。
uj5u.com熱心網友回復:
這是使用視窗函式的一種方法:
select * , count(a_id) over (partition by a_id) > 1 more_than_one_reference
from tableB
uj5u.com熱心網友回復:
您可以使用 self- join:
select b1.id, sum(case when b2.a_id is null then 0 else 1 end) > 0
from b b1 left join b b2 on b1.a_id = b2.a_id and b1.id != b2.id group by b1.id;
或者,使用子查詢:
select b1.id, (select sum(b2.a_id = b1.a_id) from b b2) > 1 from b b1
uj5u.com熱心網友回復:
使用行內子查詢
declare @tmp1 as table(id int)
declare @tmp2 as table(id bigint identity (1,1),a_id int)
insert into @tmp1 values(1),(2),(3)
insert into @tmp2 values(1),(1),(2),(2),(2),(3),(null),(null)
select more_than_one_reference=(select case when count(*)>1 then 'true' else 'false' end from @tmp2 tmp3 where tmp3.a_id=tmp2.a_id)
from @tmp2 tmp2
join @tmp1 tmp1
on tmp2.a_id=tmp1.id
輸出
more_than_one_reference
true
true
true
true
true
false
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/366111.html
標籤:sql PostgreSQL的
上一篇:從不同的表中獲取虛擬列
下一篇:Postgres列出序列依賴項
