简体   繁体   English

仅当所有连接的条具有相同的列值时才返回foo

[英]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个表foobar ,两者之间存在一对多的关系。 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. 我一直在查看CASEIF查询,但不知道如何使它们在这种情况下起作用。

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.

相关问题 SQL - 如果列没有相同的值,则仅返回行 - SQL - Only Return Row If Column Does Not Have Same Value SQL-如果一列中所有具有相同“订单号”的行在另一列中具有相同的“插槽”,则返回一个值 - SQL - Return a value if all rows that have the same “order number” in one column have the same “slot” in another 仅当具有相同ID的所有项目在另一列中都具有相同的值时,才返回行 - Only return rows if all items with the same ID has all the same value in another column 在 SQL 中获取列 A 中具有相同值的所有行,这些行在列 B 中只有非空值 - In SQL get all rows with same value in column A that have only non-null values in column B SQL 查询:返回其他列中与value2相同的values1,仅当values1不同时 - SQL QUERY: return the values1 which have the same value2 in other column, only if the values1 are different 仅当所有记录具有相同值时才给出答案 - An answer only if all records have the same value 仅当具有相同第 1 列的所有行中的第 2 列为 NULL 时才返回第 1 列 - Return column 1 only if column 2 is NULL in all rows with the same column 1 过滤所有行的特定条件,并为具有相同值的每一列仅返回一行 - Filtering down specific criteria for all rows and return only one row for each column with the same value 如何检查联接表中的所有帖子在列中是否具有相同的值? - How do I check if all posts from a joined table has the same value in a column? SQL仅选择具有相同列值的行 - SQL select only rows which have same column value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM