Sql 仅当on列的值与其他列的值不同时才选择
我有一个链接表,其规则id与子规则id相同: 我希望能够获得所有子规则id,这些子规则id只链接到一个规则。因此,如果我的规则id=1,那么我希望没有行。如果rule_id=2,那么我应该只得到一个。尝试使用distinct和having,并且不会因为错误的查询而困扰您。。我相信有一个简单而优雅的方法可以做到这一点 提前感谢您可以按子规则id分组,并在having子句中设置条件: 如果需要整行,则不存在或:Sql 仅当on列的值与其他列的值不同时才选择,sql,postgresql,Sql,Postgresql,我有一个链接表,其规则id与子规则id相同: 我希望能够获得所有子规则id,这些子规则id只链接到一个规则。因此,如果我的规则id=1,那么我希望没有行。如果rule_id=2,那么我应该只得到一个。尝试使用distinct和having,并且不会因为错误的查询而困扰您。。我相信有一个简单而优雅的方法可以做到这一点 提前感谢您可以按子规则id分组,并在having子句中设置条件: 如果需要整行,则不存在或: select t.* from tablename t where 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
)
谢谢@forpas,根据我的示例,我应该在哪里添加where rule_id=trued for the tware with 1,然后我得到我的整个表格减去第二行a为什么整个表格减去第二行a?排除该行的逻辑是什么?它的子规则id是1,就像第一行一样。因此,它们都应该被排除在外。第4行和第5行也一样。谢谢!使用“不存在”选项管理
select sub_rule_id
from tablename
group by sub_rule_id
having count(distinct rule_id) = 1
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
)