简体   繁体   English

MySQL: ORDER BY A COUNT of rows from another table?

[英]MySQL: ORDER BY a COUNT of rows from another table?

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).基本上,我想按照它们覆盖的目标肌肉的数量来排序练习(在示例中,目标肌肉是 4 和 11)。 However, the subquery (for some reason?) doesn't know what e is, so it does not work.但是,子查询(出于某种原因?)不知道 e 是什么,所以它不起作用。

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". MySQL 中的 SQL 子查询具有类似于“本地命名空间”的内容。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM