簡體   English   中英

MySQL Join - 僅當所有右表行都滿足 WHERE 子句時才檢索左表行

[英]MySQL Join - Retrieve Left Table Rows only if all the Right Table Rows satisfies the WHERE clause

我有兩個表(表 A 和表 B),其中“表 A”中的單個父行將在“表 B”中具有多行。 我必須從“表 A”中檢索行,僅當“表 B”中的所有子行都滿足 WHERE 子句時。

表A

id     INT
name    VARCHAR
gender  VARCHAR

表B

id        INT
table_A_id INT
condition  INT

現在,我必須為 'Table B' 中的所有子行都滿足WHERE子句'condition=100'那些行獲取 'Table A' 的行。

這個查詢:

select table_A_id
from tableb
group by table_A_id
having sum(case when condition = 100 then 1 else 0 end) = count(*)

返回 tableb 中滿足條件的所有table_A_id
你可以像這樣在 IN 中使用它:

select * 
from tablea 
where id in (
  select table_A_id
  from tableb
  group by table_A_id
  having sum(case when condition = 100 then 1 else 0 end) = count(*)
)

或者你可以加入子查詢:

select a.* 
from tablea a inner join (
  select table_A_id
  from tableb
  group by table_A_id
  having sum(case when condition = 100 then 1 else 0 end) = count(*)
) b on b.table_A_id = a.id

請注意,對於 MySql,可以將 HAVING 子句簡化為:

having sum(condition = 100) = count(*)

這將做到:

select * from TableA A JOIN TableA B ON B.table_A_id = A.id 
where not exists (select 1 from TableB B where B.table_A_id = A.id and condition  <> 100)

我會簡單地推薦:

select a.*
from TableA a 
where not exists (select 1
                  from TableB B
                  where B.table_A_id = A.id and
                        condition <> 100
                 );

如果condition可以為NULL ,那么您需要:

where not exists (select 1
                  from TableB B
                  where B.table_A_id = A.id and
                        (condition <> 100 or condition is null)
                 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM