php 匹配多行,PHP-选择与相关表中的多行匹配的行
下表較大,但為方便起見已將其縮小
表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
我的問題是:如何構(gòu)造查詢,在其中可以找到每個具有Exercise_Plane_ID = 1和Exercise_Plane_ID = 2的運動的Exercise_ID.換句話說,找到既具有矢狀運動又具有額葉運動的運動.
正確的查詢
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的練習(正確的結(jié)果是“ Ice Skater”)
我繼續(xù)回答自己的問題:
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
解決方法:
您可以執(zhí)行以下操作,這將使用給定的輸入ID檢查計劃ID,并過濾掉每個練習組中的計數(shù)(如果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
標簽:inner-join,mysql,php
來源: https://codeday.me/bug/20191121/2054286.html
總結(jié)
以上是生活随笔為你收集整理的php 匹配多行,PHP-选择与相关表中的多行匹配的行的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java去除不为null,JAVA代码中
- 下一篇: php读取zip文件,php如何读取zi