选择同时具有Y和Z的X(SQL)

时间:2015-11-11 18:51:13

标签: php mysql sql

好的,我有三张表,ColorsPeopleLikes

Colors包含ID和名称颜色,People包含ID和人名,Likes包含color_idpeople_id来描述哪些人喜欢哪种颜色

现在,给定一个颜色列表,我如何选择喜欢列表中每种颜色的每个人(如果有的话)?

3 个答案:

答案 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')