[英]return foo only if all joined bar have the same column value
I have 2 tables foo
and bar
, there is a one to many relation between the two. 我有2个表
foo
和bar
,两者之间存在一对多的关系。 I want to get a list of foos where all the corresponding bars have a column status = 'CLOSED'
. 我想获取所有对应栏都具有列
status = 'CLOSED'
的foos列表。 How should I write that query? 我应该如何编写该查询?
SELECT f.*
FROM foo f
JOIN bar b ON b.foo_bk = f.bk
WHERE b.status = 'CLOSED'
The current query will return the foo
even if it has one bar
with a different status
value. 即使当前查询具有一个带有不同
status
值的bar
,它也会返回foo
。 I have been looking at CASE
and IF
queries but I don't know how to get them to work for this case. 我一直在查看
CASE
和IF
查询,但不知道如何使它们在这种情况下起作用。
Try to add subquery as below 尝试如下添加子查询
SELECT f.*
FROM foo f
JOIN bar b ON b.foo_bk = f.f_bk
WHERE b.status = 'CLOSED'
AND not exists (select 1
from bar b2
where b2.foo_bk = f.f_bk
and b.status <> 'CLOSED')
SELECT f.* FROM foo f
JOIN bar b ON b.foo_bk = f.f_bk
WHERE f.f_bk IN (SELECT b.bk FROM bar b WHERE b.status = 'CLOSED')
AND f.f_bk NOT IN (SELECT b.bk FROM bar b WHERE b.status <> 'CLOSED')
This query will give you all the rows that exist in bar with status 'CLOSED', while omitting rows with other statuses. 此查询将为您提供状态为“已关闭”的条中存在的所有行,而忽略其他状态的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.