繁体   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