Selecting exercises that include the same muscles as the specified exercise (two tables)
two tables:
Exercises
---------
Exercise ID
1
ExerciseTargettedMuscles
------------------------
exerciseID muscleID
1 10
1 20
1 30
I need to grab exercises that include all of the muscles it targets. so, if exercise a has e开发者_如何学JAVAxerciseID=1 and has muscleIDs=10,20, and 30, then the result of the query should be exercises with (at least) muscleIDs=10,20, and 30.
What confuses me is the multiple-to-multiple row comparing. The way that works in my head is to just make sure that there doesn't exist a muscle in the main exercise that is not present in the selected exercise(s). How do you loop through every one to see if it is not in the selected exercise?
Using HAVING to filter your results to only include those with at least the desired muscles:
select exerciseID
from ExerciseTargettedMuscles
where muscleID in (10, 20, 30)
group by exerciseID
having count(muscleID) = 3
The 3
should match the number of muscles.
The WHERE gives you the exercises that have any of the desired muscles. Then they are grouped into one group for each exercise. Finally the HAVING is used to include only those groups that have all (rather than just some) the muscles.
精彩评论