Mysql复杂排序

时间:2016-01-21 04:58:23

标签: php mysql sorting

我有这样的查询

SELECT videos.*, 
       (SELECT COUNT(comment_id) 
        FROM comments 
        WHERE comments.comments_video_id = videos.id) AS video_comments
FROM videos
ORDER BY video_comments DESC

现在,如果我有两行具有相同的'videos_comments'计数,那么如何写这个以便在这两个视频之间,首先显示在评论表中具有最新评论(comments_date)的视频

2 个答案:

答案 0 :(得分:0)

coqtop -v
The Coq Proof Assistant, version 8.4pl4 (July 2014)
compiled on Jul 27 2014 23:12:44 with OCaml 4.01.0

答案 1 :(得分:0)

SELECT videos.id, 
       MAX(comments_date) as latest_comment, 
       COUNT(*) as video_comments 
FROM videos 
LEFT JOIN comments 
       ON comments.comments_video_id = videos.id
GROUP BY videos.id
ORDER BY 
      video_comments,   
      latest_comment    

如果你想要视频。*

SELECT videos.*,
       video_comments,   
       latest_comment 
FROM videos
JOIN (
        SELECT videos.id, 
               MAX(comments_date) as latest_comment, 
               COUNT(*) as video_comments 
        FROM videos 
        LEFT JOIN comments 
               ON comments.comments_video_id = videos.id
        GROUP BY videos.id

      ) T
   ON videos.video_id = T.video_id
ORDER BY 
      video_comments,   
      latest_comment