找到所有有红球和蓝球的罐子

Find all jars that have red balls and blue balls

通过这个简单的查询,我可以找到所有包含 红球 蓝球的罐子的 ID:

SELECT id FROM "Jars" J
JOIN "Balls" B ON B.jarId = J.jarId
WHERE B.color = 'red' OR B.color = 'blue'
GROUP BY id

如何找到所有包含 红球 蓝球的罐子的 ID?

如果两者都是你想要的,那就试试吧:

SELECT id
  FROM (
SELECT j.id,
       COUNT(CASE WHEN b.colour = 'red' THEN b.id ELSE NULL END) as reds,
       COUNT(CASE WHEN b.colour = 'blue' THEN b.id ELSE NULL END) as blues
  FROM Jars j INNER JOIN Balls b ON j.jarId = b.jarId
WHERE b.color IN ('red', 'blue')
GROUP BY j.id) tmp
 WHERE tmp.reds > 0 and tmp.blues > 0;

您不需要子查询。您甚至不需要 JOIN,因为您只需要罐子的 ID(在 balls table)

中可用
select b.jarid
from balls b
where b.color in ('blue', 'red')
group by b.jarid
having count(*) = 2

请注意,这也会 return 具有其他颜色(例如蓝色、红色和黄色)的球。

如果您只想要正好蓝色和红色的那些,您可以使用这个:

select jarid
from balls
group by jarid
having count(*) = 2 
and bool_and(color in ('blue', 'red'))