如何按类型排序 - sql

时间:2017-05-04 13:42:32

标签: sql mysqli

我正在处理按flag_color排序的查询,但我希望它按颜色优先:

此查询现在返回:

SELECT   flag_color as color 
FROM     clinic_performance_flags 
GROUP BY clinic_user_id 
ORDER BY flag_color ASC


green
green
green
green
red
red
red
red
yellow
yellow
yellow

但我想更改顺序,因此订单变为(red应始终为第一,yellow秒和green第三)示例:

red
red
red
red
yellow
yellow
yellow
yellow
green
green
green
green

3 个答案:

答案 0 :(得分:0)

使用FIELD功能。

SELECT flag_color AS color 
FROM clinic_performance_flags 
GROUP BY clinic_user_id 
ORDER BY FIELD(flag_color ,'red','yellow','green'), flag_color ASC

答案 1 :(得分:0)

CASE

中使用ORDER BY
SELECT   flag_color as color 
FROM     clinic_performance_flags 
GROUP BY clinic_user_id 
ORDER BY CASE WHEN flag_color = 'red'    THEN 1
              WHEN flag_color = 'yellow' THEN 2
              WHEN flag_color = 'green'  THEN 3
                                         ELSE 4
         END, flag_color ASC

答案 2 :(得分:0)

您可以使用CASE声明

SELECT   flag_color as color 
FROM     clinic_performance_flags 
GROUP BY clinic_user_id 
ORDER BY CASE WHEN flag_color = 'red' THEN 1
              WHEN flag_color = 'yellow' THEN 2
              WHEN flag_color = 'green' THEN 3
              ELSE 4 END