PHP, MYSQL: Order by date but empty dates last not first

前端 未结 5 2288
暗喜
暗喜 2021-02-19 19:30

I fetch an array with todo titles and due dates from MySQL. I want to order it by date and have the oldest on top. But there are some todos without a date. These todos I don\'t

相关标签:
5条回答
  • 2021-02-19 19:40

    You can do it in MySQL with the ORDER BY clause. Sort by NULL first, then the date.

    SELECT * FROM your_table ORDER BY (date_column IS NULL), date_column ASC
    

    Note: This assumes rows without a date are NULL.

    0 讨论(0)
  • 2021-02-19 19:43

    Yes

    SELECT * 
      FROM table 
      ORDER BY  CASE your_date 
                  WHEN '' THEN 'b' 
                  ELSE 'a' 
                END,
                date ASC 
    
    0 讨论(0)
  • 2021-02-19 19:43

    possibly add a NVL( thedate, to_date('2099-12-31','yyyy-mm-dd')) in the order by clause

    0 讨论(0)
  • 2021-02-19 19:46

    You can use this:

    select * from my_table
    order by if(isnull(my_field),1,0),my_field;
    
    0 讨论(0)
  • 2021-02-19 19:50

    Well, as a pure MySQL answer, I would probably do it like this.

      select todo.title, todo.due_date
        from todo
        order by ifnull(todo.due_date, '9999-12-31')
    
    0 讨论(0)
提交回复
热议问题