我有两张桌子,PC和SC。在SC中,我有3种颜色(红色,蓝色,绿色)的列表。在PC中,我有两列名称和颜色,如下所示:
Name Color
Tom Red
Tom Blue
Tom Green
Mike Red
Mike Blue
James Green
Joe Red
Joe Blue
Joe Green
James Brown
我需要从PC返回名称,其中Color列包含SC中的所有颜色。如何实现这一目标?
这就是我的尝试,但它不起作用。
SELECT DISTINCT PC.Name
FROM PC
INNER JOIN SC ON PC.ColorCode = SC.ColorCode
WHERE PC.ColorCode IN (SELECT ColorCode FROM SC);
请帮忙。
答案 0 :(得分:4)
您需要使用HAVING子句来过滤组
select name from pc
group by Name
having count(distinct color) = (SELECT count(distinct color) FROM SC)
答案 1 :(得分:0)
您可以使用exists
:
select distinct name
from pc p1
where not exists(select * from sc
where colorcode not in(select color from pc p2
where p1.name = p2.name))
答案 2 :(得分:0)
这应该有用。
SELECT P.NAME
FROM PC P
LEFT JOIN SC S ON P.COLOR=S.COLOR
WHERE S.COLOR IS NOT NULL
GROUP BY P.NAME