好的,我有三张表,Colors
,People
,Likes
Colors
包含ID和名称颜色,People
包含ID和人名,Likes
包含color_id
和people_id
来描述哪些人喜欢哪种颜色
现在,给定一个颜色列表,我如何选择喜欢列表中每种颜色的每个人(如果有的话)?
答案 0 :(得分:3)
select p.id, p.name
from people p
join likes l on l.people_id = p.id
join colors c on l.color_id = c.id
where c.name in ('blue','green','red')
group by p.id, p.name
having count(distinct c.name) = 3
答案 1 :(得分:1)
您可以对喜欢加入的人进行GROUP BY,并检索那些具有等于颜色列表中行数的COUNT(*)的元组。这样你
SELECT People.id, COUNT(*) AS ColorsLiked
FROM People JOIN Likes ON (People.id = Likes.people_id)
GROUP BY People.id
HAVING ColorsLiked = (SELECT COUNT(*) FROM Colors);
答案 2 :(得分:0)
SELECT * FROM People p
INNER JOIN Likes l ON l.people_id = p.people_id
INNER JOIN Colors c ON l.color_id = c.color_id
WHERE c.name IN ('List of colors')