![](/img/trans.png)
[英]Find all records where one-to-many join table satisfies one condition, but not another condition
[英]Select records where every record in one-to-many join matches a condition
仅当表B
中的每个关联记录都与条件匹配时,如何编写SQL查询以返回表A
中的记录?
我正在Ruby中工作,并且可以将这种逻辑编码为一个简单的集合,如下所示:
array_of_A.select { |a| a.associated_bs.all? { |b| b.matches_condition? } }
我在构造中是通用的,因为我正在开发一种通用工具,该工具将在许多不同的情况下使用。
我知道情况是, INNER JOIN
等于
array_of_A.select { |a| a.associated_bs.any? { |b| b.matches_condition? } }
我都尝试过:
SELECT DISTINCT "A".* FROM "A"
INNER JOIN "B"
ON "B"."a_id" = "A"."id"
WHERE "B"."string' = 'STRING'
以及:
SELECT DISTINCT "A".* FROM "A"
INNER JOIN "B"
ON "B"."a_id" = "A"."id"
AND "B"."string' = 'STRING'
在这两种情况下(正如我预期的那样),如果来自B
任何关联记录都符合条件,它将返回表A
记录。 我敢肯定有一个相对简单的解决方案,但是我目前对SQL的了解还不够。 事实证明,我通过SO和Google进行的所有搜索都没有结果。
我建议以下内容:
select distinct a.*
from a inner join
(
select b.a_id
from b
group by b.a_id
having min(b.string) = max(b.string) and min(b.string) = 'string'
) c on a.id = c.a_id
或者:
select distinct a.*
from a inner join b on a.id = b.a_id
where not exists (select 1 from b c where c.a_id = a.id and c.string <> 'string')
注意:在以上示例中,仅将符号a
和b
更改为表的名称; 其他标识符仅是别名,不应更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.