如何按计数行选择数据顺序
我想按计数media_user_action
行选择数据顺序,不知道如何在一个查询语法中执行此操作
e.g
media_id 1 media_user_action中的3行
media_id 2 media_user_action中的1行
返回数据
media_id 1然后是media_id 2
SELECT
m.*
FROM media m
LEFT JOIN media_user_action mua ON mua.media_id = m.id
// ORDER BY COUNT(mua.*) count rows desc ?
媒体
id |
1
2
media_user_action
id | media_id | user_id | type
1 | 1 | 1 | 0
2 | 1 | 13 | 0
3 | 1 | 15 | 1
4 | 2 | 16 | 0
答案 0 :(得分:3)
您可以在COUNT
子句中使用ORDER BY
:
SELECT m.id
FROM media m
LEFT JOIN media_user_action mua
ON mua.media_id = m.id
AND mua.type = 0
GROUP BY m.id
ORDER BY COUNT(mua.id) DESC
如果您想为media_user_action
添加其他条件,请将其添加到ON
子句中:
SELECT m.id
FROM media m
LEFT JOIN media_user_action mua
ON mua.media_id = m.id
GROUP BY m.id
ORDER BY COUNT(mua.id) DESC