[英]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.