MySQL order by before group by

后端 未结 9 2247
梦谈多话
梦谈多话 2020-11-22 06:57

There are plenty of similar questions to be found on here but I don\'t think that any answer the question adequately.

I\'ll continue from the current most popular qu

9条回答
  •  一向
    一向 (楼主)
    2020-11-22 07:40

    ** Sub queries may have a bad impact on performance when used with large datasets **

    Original query

    SELECT wp_posts.*
    FROM   wp_posts
    WHERE  wp_posts.post_status = 'publish'
           AND wp_posts.post_type = 'post'
    GROUP  BY wp_posts.post_author
    ORDER  BY wp_posts.post_date DESC; 
    

    Modified query

    SELECT p.post_status,
           p.post_type,
           Max(p.post_date),
           p.post_author
    FROM   wp_posts P
    WHERE  p.post_status = "publish"
           AND p.post_type = "post"
    GROUP  BY p.post_author
    ORDER  BY p.post_date; 
    

    becasue i'm using max in the select clause ==> max(p.post_date) it is possible to avoid sub select queries and order by the max column after the group by.

提交回复
热议问题