MySQL conditional ORDER BY ASC/DESC for date column

后端 未结 4 1752
太阳男子
太阳男子 2020-12-19 04:33

I need a MySQL conditional ORDER BY statement for a datetime field. I have a table with posts which I would like to order in the following way: all future posts

相关标签:
4条回答
  • 2020-12-19 05:11

    i would use an union all, tricks in order by can't use index and is slower.

    SELECT * FROM
    ((SELECT
      1 AS a, @rownum:=@rownum+1 B, post_status, post_date, post_title
    FROM
      wp_posts, (SELECT @rownum:=0) r 
    WHERE
      post_status='publish'
    ORDER BY
      post_date DESC)
    UNION ALL
    (SELECT
      2 AS a,  @rownum:=@rownum+1 B, post_status, post_date, post_title
    FROM
      wp_posts, (SELECT @rownum:=0) r2
    WHERE
      post_status='future'
    ORDER BY
      post_date)) ORDER BY A,B;
    
    0 讨论(0)
  • 2020-12-19 05:19

    How about something like this? Select twice and union the results.

    Select * from (SELECT post_status, post_date, post_title 
    FROM wp_posts WHERE post_status IN ('future') 
    ORDER BY post_status ASC  ) alias1  
    UNION
    Select * from (SELECT post_status, post_date, post_title 
    FROM wp_posts WHERE post_status IN ('publish') 
    ORDER BY post_status DESC ) alias2  
    
    0 讨论(0)
  • 2020-12-19 05:21

    Try this one -

    SELECT
      post_status, post_date, post_title
    FROM
      wp_posts
    WHERE
      post_status IN ('future', 'publish')
    ORDER BY
      IF(post_status = 'future', 0, 1),
      IF(post_status = 'future', TO_DAYS(post_date), TO_DAYS(post_date) * -1);
    
    0 讨论(0)
  • 2020-12-19 05:22

    Try this:

    ORDER BY post_status ASC,
    CASE post_status WHEN 'future' THEN POST_DATE END ASC,
    CASE WHEN post_status <> 'future' THEN post_date END DESC
    
    0 讨论(0)
提交回复
热议问题