MySQL:列出具有一个但不是另一个多对多关系的行

时间:2011-01-04 20:51:55

标签: mysql sql join many-to-many

不太确定如何询问或定义,但无法弄明白。

我有三张这样的表:

persons             person_id, first_name, last_name
hobbies             hobby_id, name
persons_hobbies     person_id, hobby_id

我需要制作两个清单。既有爱好A又有B的人,以及有爱好但不爱B的人。我怎么能写出这两个问题呢?无法弄清楚如何加入和所有这一切......

说爱好A有id = 3而爱好B有id = 7。

2 个答案:

答案 0 :(得分:6)

这样的事情应该有效:

-- Persons that have both hobby A and B
select p.first_name,p.last_name
from persons p
inner join persons_hobbies ph1 on ph1.person_id = p.person_id and ph1.hobby_id = 3
inner join persons_hobbies ph2 on ph2.person_id = p.person_id and ph2.hobby_id = 7;

-- Persons that have hobby A but not B 
select p.first_name,p.last_name
from persons p
inner join persons_hobbies ph1 on ph1.person_id = p.person_id and ph1.hobby_id = 3
left outer join persons_hobbies ph2 on ph2.person_id = p.person_id and ph2.hobby_id = 7
where ph2.person_id is null;

答案 1 :(得分:0)

如果您使用子查询,我发现此类型更易于理解和编码。

SELECT * FROM Persons
WHERE person_id IN (SELECT person_id FROM person_hobbies WHERE hobby_id ...)

但如果你必须加入 - 艾克钉了它。