简体   繁体   English

选择其中一对多连接中的每个记录都符合条件的记录

[英]Select records where every record in one-to-many join matches a condition

How can I write a SQL query that returns records from table A only if every associated record from table B matches a condition? 仅当B中的每个关联记录都与条件匹配时,如何编写SQL查询以返回表A中的记录?

I'm working in Ruby, and I can encode this logic for a simple collection like so: 我正在Ruby中工作,并且可以将这种逻辑编码为一个简单的集合,如下所示:

array_of_A.select { |a| a.associated_bs.all? { |b| b.matches_condition? } }

I am being generic in the construction, because I'm working on a general tool that will be used across a number of distinct situations. 我在构造中是通用的,因为我正在开发一种通用工具,该工具将在许多不同的情况下使用。

What I know to be the case is that INNER JOIN is the equivalent of 我知道情况是, INNER JOIN等于

array_of_A.select { |a| a.associated_bs.any? { |b| b.matches_condition? } }

I have tried both: 我都尝试过:

SELECT DISTINCT "A".* FROM "A"
INNER JOIN "B"
  ON "B"."a_id" = "A"."id"
WHERE "B"."string' = 'STRING'

as well as: 以及:

SELECT DISTINCT "A".* FROM "A"
INNER JOIN "B"
  ON "B"."a_id" = "A"."id"
  AND "B"."string' = 'STRING'

In both cases (as I expected), it returned records from table A if any associated record from B matched the condition. 在这两种情况下(正如我预期的那样),如果来自B 任何关联记录都符合条件,它将返回表A记录。 I'm sure there's a relatively simple solution, but my understanding of SQL just isn't providing it to me at the moment. 我敢肯定有一个相对简单的解决方案,但是我目前对SQL的了解还不够。 And all of my searching thru SO and Google has proven fruitless. 事实证明,我通过SO和Google进行的所有搜索都没有结果。

I would suggest the following: 我建议以下内容:

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

Alternatively: 或者:

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')

Note: In the above examples, only change the symbols a and b to the names of your tables; 注意:在以上示例中,仅将符号ab更改为表的名称; the other identifiers are merely aliases and should not be changed. 其他标识符仅是别名,不应更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM