[英]Joining versus Union on two MySQL tables with GROUP BY and ORDER BY conditions
[英]Joining two tables in MySQL with conditions
首先:
id_look id_first name
1 1 Jhon
2 2 Mark
3 3 Mike
第二
id id_first surnames
1 2 AAA
2 2 BBB
3 2 CCC
4 1 DDD
5 1 AAA
6 1 BBB
7 3 BBB
如果姓是AAA
AND BBB
我想獲取所有id_look
(相同的id_first
)
所以結果應該是:
id_look
1
2
因為只有該id_look
包含AAA
AND BBB
。
SELECT id_look
FROM `first` f
JOIN `second` s
ON s.id_first = f.id_first
WHERE surnames IN ( 'AAA', 'BBB' )
GROUP BY id_look
HAVING COUNT(DISTINCT surnames) = 2;
這有點丑陋,但是可以滿足您的要求。
select id_look
from first
inner join second as second_aaa
on second_aaa.id_first = first.id_first
and second_aaa.surnames = 'AAA'
inner join second as second_bbb
on second_bbb.id_first = first.id_first
and second_bbb.surnames = 'BBB'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.