MySQL:按另一个表中的行数排序?
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 是什么,所以它不起作用。
关于如何让这个查询正确排序我的结果有什么想法吗?谢谢!
编辑:在兰迪的有用评论后想出了这个。
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
非常感谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
了解表格的结构可能会有所帮助。我建议一个与此类似的解决方案。
Knowing how the tables are structured might be helpful. I suggest a solution similar to this.
如果我理解正确的话,你根本不需要子查询
If I understand correctly, you don't need subquery at all
MySQL 中的 SQL 子查询有类似“本地命名空间”的东西。我没有能力进行测试,但您可能正在搜索类似这样的内容:
但是,在某些情况下,您根本不必使用子查询。
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:
But, in some cases, you do not have to use subquery at all.