我有三张桌子:

project (idproject, name)

color (idcolor, name)

project_has_color (idproject, idcolor)

现在我需要选择与一组颜色相关的项目,例如:蓝色(1)、红色(2)、绿色(3):
SELECT p.idproject, p.name
FROM project p, project_has_color c
WHERE p.idproject=c.idproject AND c.idcolor IN (1,2,3)

为我提供与一个或多个给定idcolor相关的项目,我需要与所有这些项目相关的项目-但我不知道如何实现这一点?

最佳答案

使用联接是最可靠的方法:

SELECT p.idproject,
       p.name
  FROM PROJECT p
  JOIN PROJECT_HAS_COLOR phc ON phc.idproject = p.idproject
  JOIN COLOR c1 ON c1.idcolor = phc.idcolor
               AND c1.idcolor = 1
  JOIN COLOR c2 ON c2.idcolor = phc.idcolor
               AND c2.idcolor = 2
  JOIN COLOR c3 ON c3.idcolor = phc.idcolor
               AND c3.idcolor = 3

使用:
  SELECT p.idproject,
         p.name
    FROM PROJECT p
    JOIN PROJECT_HAS_COLOR phc ON phc.idproject = p.idproject
    JOIN COLOR c ON c.idcolor = phc.idcolor
   WHERE c.idcolor IN (1, 2, 3)
GROUP BY p.idproject, p.name
  HAVING COUNT(*) = 3

…依赖于您的数据模型停止将idcolor值与项目关联多次。在mysql中不能使用HAVING COUNT(DISTINCT *),因此同一项目的2+关系复制idcolor值将返回误报。

10-02 22:30