簡體   English   中英

僅當列值與其他列不同時才選擇

[英]Selecting only if on column value is distinct by other column

我有一個帶有rule_idsub_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那么我應該只得到一個。 嘗試使用distincthaving並且不會因錯誤的查詢而給您帶來麻煩。我相信有一種簡單而優雅的方法可以做到這一點。

提前致謝

您可以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.

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