按多列MySQL排序

时间:2017-10-01 11:24:33

标签: mysql sql sorting sql-order-by

我有一个表,其中我有三个数据类型为INT,INT和INT的字段。

我想使用所有这三列对我的选择查询进行排序。如果字段A <= 10,则按ASC排序,按DESC字段2排序并按ASC字段3排序。

SELECT * FROM table1 WHERE id=uid     
ORDER BY 
    CASE table1.field1
        WHEN table1.field1 < 11 THEN table1.field1
        END
    ASC, 
table1.field2 DESC,
table1.field3 ASC;

+------+--------+---------+
|field1| field2 | field3  |
+------+--------+---------+
|   1  |    4   |    1    |
+------+--------+---------+
|   2  |    3   |    2    |
+------+--------+---------+
|   9  |    2   |    4    |
+------+--------+---------+
|  10  |    1   |    7    |
+------+--------+---------+

由于某种原因,CASE并不真正起作用,如果我排除它有效,但会按ASC顺序对所有field1进行排序,而我只想要10先进行。

1 个答案:

答案 0 :(得分:2)

table1.field1之前不需要WHEN

SELECT * 
FROM table1 
WHERE id = uid     
ORDER BY CASE WHEN table1.field1 < 11 THEN table1.field1 END ASC, 
  table1.field2 DESC,
  table1.field3 ASC;

说明:

CASE table1.field1
     WHEN table1.field1 < 11 THEN table1.field1
END       -- this evaluates to true/false (1 and 0)

=>
CASE table1.field1 WHEN 1 THEN table1.field1 END