SELECT e.*,
(
SELECT COUNT(*) FROM
(
SELECT tm.exerciseID FROM exercise_targetedmuscles tm
WHERE tm.exerciseID = e.exerciseID
AND tm.isPrimary = 1
AND tm.targetedMuscleID IN (4,11)
) as musclesCovered
) as numMusclesCovered
FROM exercises e
ORDER BY numMusclesCovered DESC
Basically, I want to order the exercises by the number of targetted muscles they cover (in the example, the targetted muscles are 4 and 11). However, the subquery (for some reason?) doesn't know what e is, so it does not work.
Any ideas as to how I can get this query to order my results properly? Thanks!
EDIT: came up with this after Randy's helpful comment.
SELECT COUNT(tm.targetedMuscleID) as numMusclesCovered, e.*, tm.* FROM exercise_targetedmuscles tm
JOIN exercises e ON tm.exerciseID = e.exerciseID
WHERE tm.isPrimary = 1
AND tm.targetedMuscleID IN (4,11)
GROUP BY tm.exerciseID
ORDER BY numMusclesCovered DESC
thanks so much!
SQL subqueries in MySQL has something like "local namespace". I haven`t got ability to test, but you may be searching for something like this:
SELECT `data`.* FROM (
SELECT COUNT(tm.targetedMuscleID) as `count`,tm.targetedMuscleID FROM exercise_targetedmuscles tm
LEFT JOIN `exercises` as `e` ON (`tm`.`exerciseID`=`e`.`exerciseID`)
WHERE
tm.isPrimary = 1
AND
tm.targetedMuscleID IN (4,11)
GROUP BY tm.targetedMuscleID
) as `data`
ORDER BY `data`.`count`
But, in some cases, you do not have to use subquery at all.
Knowing how the tables are structured might be helpful. I suggest a solution similar to this.
SELECT e.*, tm.*, COUNT(tm.targetedMuscleID) AS coveredMuscles
FROM exercises AS e
JOIN exercise_targetedmuscles AS tm ON tm.exerciseID = e.exerciseID
WHERE tm.isPrimary = 1 AND tm.targetedMuscleID IN (4, 11)
GROUP BY e.exerciseID
ORDER BY coveredMuscles;
If I understand correctly, you don't need subquery at all
SELECT count(tm.targetedMuscleID) as num_muscles, e.exerciseID
FROM exercise_targetedmuscles tm, exercises e
WHERE tm.exerciseID = e.exerciseID
AND tm.isPrimary = 1
AND tm.targetedMuscleID IN (4,11)
GROUP BY e.exerciseID
order by num_muscles
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.