Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 仅当on列的值与其他列的值不同时才选择_Sql_Postgresql - Fatal编程技术网

Sql 仅当on列的值与其他列的值不同时才选择

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

我有一个链接表,其规则id与子规则id相同:

我希望能够获得所有子规则id,这些子规则id只链接到一个规则。因此,如果我的规则id=1,那么我希望没有行。如果rule_id=2,那么我应该只得到一个。尝试使用distinct和having,并且不会因为错误的查询而困扰您。。我相信有一个简单而优雅的方法可以做到这一点

提前感谢

您可以按子规则id分组,并在having子句中设置条件:

如果需要整行,则不存在或:

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
)