如果结果小于,则在MYSQL中使用OR语句IF语句

时间:2018-06-14 06:43:11

标签: mysql

我的表格看起来有点像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    |
+---------+---------------+------------+---------------+

2 个答案:

答案 0 :(得分:1)

尝试这个逻辑:

SELECT *
FROM yourTable
ORDER BY
    CASE WHEN DATEDIFF(due_date, CURDATE()) <= 1
         THEN due_date
         ELSE received_date END;

但是,我得到的输出与你期望的不同:

enter image description here

Demo

答案 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;