简体   繁体   English

按多列排序MySQL

[英]Sort by multiple columns MySQL

I have a table in which I have three fields with data type INT, INT and INT. 我有一个表,其中有三个字段,数据类型为INT,INT和INT。

I want to sort my select query using all these three columns. 我想使用所有这三列对我的选择查询进行排序。 Sort by ASC if field A <= 10, sort by DESC field2 and sort by ASC field 3. 如果字段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    |
+------+--------+---------+

For some reason the CASE doesnt really work, if I exclude that it works but does sort all of field1 in ASC order while I only want the 10 first. 由于某种原因, CASE真正起作用,如果我排除了它的作用,但确实按ASC顺序对所有field1进行了排序,而我只想先输入10。

There is no need for table1.field1 before WHEN : WHEN之前不需要table1.field1

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

Explanation: 说明:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM