简体   繁体   English

SQL根据列值对结果集进行排序

[英]SQL order a result set based on a column value

I am using mysql, is there a way we can order the result set based on the value of a column. 我正在使用mysql,有没有一种方法可以根据列的值对结果集进行排序。

I want the rows to be in the end or beginning of the result where 我希望行位于结果的结尾或开头,其中

col = 'SOMEVALUE'

If my question is not clear, consider the following scenario: 如果我的问题不清楚,请考虑以下情形:

I have a surveys table, that has a status column, I want to get all surveys, but the ones with status = 'Expired' need to be at the end of the result set. 我有一个surveys表,其中有一个status列,我想获取所有调查,但是status = 'Expired'必须在结果集的末尾。

Is there an SQL way of doing this? 是否有执行此操作的SQL方法? or I need to sort the result manually after retrieval? 还是检索后需要手动对结果进行排序?

You can use an expression in the order by . 您可以按order by使用表达式。 In MySQL, this is particularly simple: 在MySQL中,这特别简单:

order by (status = 'Expired') asc,  -- put status at the end
         status  -- or however you want the rows ordered.

This works because MySQL treats a boolean expression as a number in a numeric context, with 1 for "true" and 0 for "false". 这是可行的,因为MySQL在数字上下文中将布尔表达式视为数字,其中1表示“ true”,0表示“ false”。

If you have more column value then you can use case in the sorting. 如果您有更多的列值,则可以在排序中使用case

or you can use this also. 或者您也可以使用它。

CREATE TABLE kaka
(
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
col_2 VARCHAR(200)
);

INSERT INTO kaka(col_2) VALUES
('a'),
('v'),
('x'),
('aa')


SELECT col_2, CASE col_2 WHEN 'x' THEN 1 WHEN 'aa' THEN 2 WHEN 'v' THEN 3 ELSE 4 END sort
FROM kaka
ORDER BY sort

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

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