输入时的情况({数字集})

时间:2019-02-04 14:25:33

标签: mysql

我需要在MySQL中使用以下case语句。

当列值为(1、2、5、7、14、17)时-返回0,否则返回1,我需要在order by子句中使用它。

我的第一印象是进行如下查询:

SELECT ... ORDER BY (CASE column WHEN IN (1, 2, 5, 7, 14, 17) THEN 0 ELSE 1 END) DESC

但这显然失败了。

我可以这样写:

SELECT ... ORDER BY (CASE column WHEN 1 THEN WHEN 2 THEN 0 WHEN 5 THEN ... 0 ELSE 1 END) DESC

但是我正在寻找一种更优雅的方式。还有其他优雅的语法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用nested query,例如:

SELECT B.*
FROM (
    SELECT A, CASE WHEN B IN (1, 2, 5, 7, 14, 17) THEN 1 ELSE 0 END AS ORDERING
    FROM TABLE
) B
ORDER BY B.ORDERING DESC;

答案 1 :(得分:1)

这需要工作

SELECT ... 
ORDER BY 
CASE WHEN (column IN (1, 2, 5, 7, 14, 17) THEN 0 ELSE 1 END) DESC

演示:

with cte0 as 
(
  select 120 x from dual union
  select 1 from dual union
  select 22 from dual union
  select 7 from dual
)
select * from cte0
order by (case when x in (22) then 0 else 1 end) desc;
|   X |
| --: |
|   1 |
| 120 |
|   7 |
|  22 |

db <>提琴here