MySQL选择与相关表中的多行匹配的行

时间:2014-05-07 05:26:22

标签: php mysql inner-join

以下表格要大得多,但为了便于解决问题,我们已缩小规模

表1 - exercise_rolladex

Exercise_ID | Exercise_Name
---------------------------
1            Pushups
2            Turkish Get Ups
3            Squats
4            Ice Skater

表2 - exercise_planes

Exercise_Plane_ID | Exercise_Plane
----------------------------------
1                  Sagittal
2                  Frontal
3                  Transverse

表3 - exercise_has_planes

Exercise_ID | Exercise_Plane_ID
-------------------------------
1             1
2             1
2             2
2             3
3             1
4             2
4             3

我的问题是:如何构建一个Query,我可以在其中找到每个练习的Exercise_ID,其中Exercise_Plane_ID = 1 AND Exercise_Plane_ID = 2。换句话说,找到同时具有矢状面和正面运动平面的练习。

正确的查询

   SELECT e.Exercise_Name, p.Exercise_Plane 
   FROM exercise_rolladex e
   INNER JOIN exercise_has_planes h ON h.Exercise_ID=e.Exercise_ID
   INNER JOIN exercise_planes p ON p.Exercise_Plane_ID=h.Exercise_Plane_ID
   WHERE p.Exercise_Plane_ID IN(2,1)
   GROUP BY e.Exercise_ID
   HAVING COUNT(DISTINCT h.Exercise_Plane_ID ) >= 2

更新后续问题 那怎么会包括一个排除?例如,使用plane_id 2和3找到练习,但用plane_id 1排除练习(正确的结果是“溜冰者”)

我继续回答我自己的问题:

   SELECT e.Exercise_Name, p.Exercise_Plane 
   FROM exercise_rolladex e
   INNER JOIN exercise_has_planes h ON h.Exercise_ID=e.Exercise_ID
   INNER JOIN exercise_planes p ON p.Exercise_Plane_ID=h.Exercise_Plane_ID
   WHERE p.Exercise_Plane_ID IN(2,3)
       AND e.Exercise_ID NOT IN
       (SELECT Exercise_ID FROM exercise_has_planes WHERE Exercise_Plane_ID='1')
   GROUP BY e.Exercise_ID
   HAVING COUNT(DISTINCT h.Exercise_Plane_ID ) >= 2

感谢布朗斯通先生从另一个问题回答。 SQL query to exclude items on the basis of one value

1 个答案:

答案 0 :(得分:3)

你可以做这样的事情,这会用你给定的输入id检查计划id并过滤掉每个练习组中的计数如果count返回多于一个则表示练习有飞机,having子句将实现两架飞机都在练习

SELECT e.Exercise_Name, 
p.Exercise_Plane 
FROM exercise_rolladex e
INNER JOIN exercise_has_planes h ON h.Exercise_ID=e.Exercise_ID
INNER JOIN exercise_planes p ON p.Exercise_Plane_ID=h.Exercise_Plane_ID
WHERE p.Exercise_Plane_ID IN(2,1)
GROUP BY e.Exercise_ID
HAVING COUNT(DISTINCT h.Exercise_Plane_ID ) >= 2

Demo

相关问题