MySQL: List rows who have one but not another many-to-many relationship
Not quite sure how to ask or define this, but can't figure it out.
I have three tables like this:
persons person_id, first_name, last_name
hobbies hobby_id, name
persons_hobbies pe开发者_开发技巧rson_id, hobby_id
I need to make two lists. Persons that have both hobby A and B, and persons that have hobby A but not B. How can I write these two queries? Can't figure out how to do this with joining and all...
Say hobby A has id=3 and hobby B has id=7.
Something like this should work:
-- 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;
I find this type to be easier to understand and code if you use sub-queries.
SELECT * FROM Persons
WHERE person_id IN (SELECT person_id FROM person_hobbies WHERE hobby_id ...)
But if you must join - Ike nailed it.
精彩评论