[英]Selecting only if on column value is distinct by other column
我有一個帶有rule_id
到sub_rule_id
的鏈接表,如下所示:
rule_id | sub_rule_id
---------------------
1 | 1
2 | 1
2 | 2
2 | 3
3 | 3
3 | 4
我希望能夠通過rule_id
獲得僅與一個rule_is
鏈接的所有sub_rule_id
。 因此,如果我的rule_id = 1
那么我預計沒有行。 如果rule_id = 2
那么我應該只得到一個。 嘗試使用distinct
和having
並且不會因錯誤的查詢而給您帶來麻煩。我相信有一種簡單而優雅的方法可以做到這一點。
提前致謝
您可以group by sub_rule_id
並在having
子句中設置條件:
select sub_rule_id
from tablename
group by sub_rule_id
having count(distinct rule_id) = 1
或者如果您想要完整的行,則使用NOT EXISTS
:
select t.* from tablename t
where not exists (
select 1 from tablename
where sub_rule_id = t.sub_rule_id
and rule_id <> t.rule_id
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.