![](/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.