按条件和字段排序

Order by with condition and with field

我想将今天有预定日期的行的状态设置为 2,如果它不是今天的预定日期,我希望状态 1、2、3 的结果基于创建于。我怎样才能查询这个?

这是 table

的示例
table1
id | scheduled_date        | status | created_at
1  | null                  | 1      | 2021-12-20 00.00.00
2  | 2021-12-27 00.00.00   | 2      | 2021-12-19 00.00.00
3  | 2021-12-26 00.00.00   | 3      | 2021-12-23 00.00.00
4  | null                  | 1      | 2021-12-15 00.00.00

这是我目前试过的查询

SELECT *
FROM `table1`
WHERE `status` <> 0
ORDER BY CASE WHEN date(scheduled_date) = '2021-12-27' AND status = 2 then 1 END ASC,
         FIELD(status, 1, 2, 3) ASC,
         `created_at` ASC

但是我得到了第 4,1,2,3 行的结果我想要第 2,4,1,3

行的结果

如有任何帮助,我们将不胜感激。我也在尝试在 laravel 上执行此操作,因此如果非常感谢其 eloquent 查询。

I want to put the row that has scheduled date today with status 2 and if its not scheduled date today I want the result of status 1, 2, 3 base on created at.

测试这个

ORDER BY CASE WHEN DATE(scheduled_date) = '2021-12-27' AND status = 2 
              THEN 0
              ELSE status  -- or FIELD(status, 1, 2, 3)
              END,
         created_at

首先,使用布尔表达式:

DATE(scheduled_date) = '2021-12-27' AND status = 2

ORDER BY 子句中然后简单地 statuscreated_at:

ORDER BY DATE(scheduled_date) = '2021-12-27' AND status = 2 DESC,
         status,
         created_at

参见demo

我认为这里的问题是空值造成的。你能试试下面的方法吗

select *
  from `table1`
where `status` <> 0
order by CASE WHEN date(scheduled_date) = '2021-12-27' and status = 2 then 1 
              ELSE 2 
          END asc,
         FIELD(status, 1, 2, 3) asc,
         `created_at` asc