在条件中加入MySQL中的两个表

时间:2011-04-03 01:00:27

标签: php mysql sql

首先:

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

如果姓氏为id_look并且id_first

,我希望获得所有AAA(同一BBB

所以结果应该是:

id_look
1
2  

因为只有id_look同时包含AAABBB

2 个答案:

答案 0 :(得分:5)

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;  

答案 1 :(得分:1)

这有点难看,但它会做你所要求的。

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'