MySQL:ORDER BY来自另一个表的COUNT行?

时间:2011-07-19 20:17:47

标签: mysql count

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

基本上,我想根据它们所覆盖的目标肌肉的数量来命定练习(在这个例子中,目标肌肉是4和11)。但是,子查询(出于某种原因?)不知道e是什么,所以它不起作用。

有关如何获取此查询以正确排序结果的任何想法?谢谢!

编辑:在Randy的有用评论之后想出了这个。

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

非常感谢!

3 个答案:

答案 0 :(得分:0)

MySQL中的SQL子查询具有类似“本地命名空间”的东西。我没有能力进行测试,但你可能正在寻找这样的东西:

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`

但是,在某些情况下,您根本不必使用子查询。

答案 1 :(得分:0)

了解表格的结构可能会有所帮助。我建议使用类似的解决方案。

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;

答案 2 :(得分:0)

如果我理解正确,你根本不需要子查询

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