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

2020-08-13 10:31发布

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 want to show at first positions but rather at the bottom of my list. Unfortunately MySQL put the empty ones first.

Is there any way I can do it in one query (can't use MySQLi, using CI's ActiveRecord). I could run a second query for all todos without dates and put them at the bottom. But I'd like to make it in one query – if possible?

5条回答
手持菜刀,她持情操
2楼-- · 2020-08-13 10:51

Yes

SELECT * 
  FROM table 
  ORDER BY  CASE your_date 
              WHEN '' THEN 'b' 
              ELSE 'a' 
            END,
            date ASC 
查看更多
ら.Afraid
3楼-- · 2020-08-13 10:55

You can use this:

select * from my_table
order by if(isnull(my_field),1,0),my_field;
查看更多
\"骚年 ilove
4楼-- · 2020-08-13 11:03

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.

查看更多
冷血范
5楼-- · 2020-08-13 11:04

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

查看更多
家丑人穷心不美
6楼-- · 2020-08-13 11:07

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')
查看更多
登录 后发表回答