[英]MySQL Select rows that match multiple rows in related table
下面的表格要大得多,但為了便於提問而縮小了尺寸
表 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
我的問題是:我如何構建一個查詢,我可以在其中找到每個練習的 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
感謝 Brownstones 先生從一個不同的問題回答。 基於一個值排除項目的 SQL 查詢
你可以做這樣的事情,這將用你給定的輸入 id 檢查計划 id 並過濾掉每個練習組中的計數,如果計數返回超過 1,則意味着練習有平面,have 子句將滿足擁有兩個平面的場景在運動中
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.