![](/img/trans.png)
[英]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.