我的表格看起来有点像received_date DESC
+---------+---------------+------------+---------------+
| name | assignment | due_date | received_date |
+---------+---------------+------------+---------------+
| Luke | Vacuum | 2018-06-14 | 2018-01-04 |
| Mark | Wash the car | 2016-01-01 | 2018-01-03 |
| Matthew | Do the dishes | NULL | 2018-01-02 |
| John | Walk the dog | 2019-01-01 | 2018-01-01 |
+---------+---------------+------------+---------------+
我正在尝试按due_date
返回行,但仅限于due_date
过去或明天,否则请按received_date
排序。例如,我希望上表最终为
+---------+---------------+------------+---------------+
| name | assignment | due_date | received_date |
+---------+---------------+------------+---------------+
| Mark | Wash the car | 2016-01-01 | 2018-01-03 | due_date in the past
| Luke | Vacuum | 2018-06-14 | 2018-01-04 | due_date tomorrow
| Matthew | Do the dishes | NULL | 2018-01-02 | rest sorted by received_date DESC
| John | Walk the dog | 2019-01-01 | 2018-01-01 |
+---------+---------------+------------+---------------+
首先我试过
SELECT *, DATEDIFF(due_date,CURDATE()) AS due
FROM table
ORDER BY IF(due < 2, due_date, received_date) DESC, received_date DESC
但这对负数不起作用,所以我尝试将负数转为零:
SELECT *, IF(DATEDIFF(due_date,CURDATE()) > 0, DATEDIFF(due_date,CURDATE()), 0) AS due
FROM table
ORDER BY IF(due < 2, due_date, received_date) DESC, received_date DESC
但due_date
和现在(如约翰)之间的任何正数都会添加到列表的顶部,最终看起来像
+---------+---------------+------------+---------------+
| name | assignment | due_date | received_date |
+---------+---------------+------------+---------------+
| John | Walk the dog | 2019-01-01 | 2018-01-01 |
| Mark | Wash the car | 2016-01-01 | 2018-01-03 |
| Luke | Vacuum | 2018-06-14 | 2018-01-04 |
| Matthew | Do the dishes | NULL | 2018-01-02 |
+---------+---------------+------------+---------------+
答案 0 :(得分:1)
尝试这个逻辑:
SELECT *
FROM yourTable
ORDER BY
CASE WHEN DATEDIFF(due_date, CURDATE()) <= 1
THEN due_date
ELSE received_date END;
但是,我得到的输出与你期望的不同:
答案 1 :(得分:0)
试试这个:
SELECT *, IF(DATEDIFF(due_date, CURDATE()) > 0, 1, IF(DATEDIFF(due_date, CURDATE()) < 0, -1, 0)) as tmp_col FROM `to_do` order by tmp_col asc, `received_date` desc;