2

我有以下查询:

select `state` from `table1` 
where `state` in ('NC','North Carolina','TN','Tennessee','CO','Colorado','NM','New Mexico','UT','Utah')
limit 200 offset 0

我需要按state出现在我的where子句中的结果排序(即 first NC, then TN, then CO,依此类推)。

我怎样才能做到这一点?我尝试使用order by,但没有给出这个结果。

4

4 回答 4

6

您可以使用ORDER BY FIELD

SELECT `state`
FROM `table1`
WHERE `state` IN ('NC','North Carolina','TN','Tennessee','CO','Colorado','NM','New Mexico','UT','Utah')
ORDER BY FIELD(`state`, 'NC','North Carolina','TN','Tennessee','CO','Colorado','NM','New Mexico','UT','Utah');
于 2012-11-14T06:12:00.880 回答
3
SELECT col_name
FROM table_nane
WHERE col_nane IN ('NC','North Carolina','TN','Tennessee','CO','Colorado','NM','New Mexico','UT','Utah')
ORDER BY FIELD(`state`, 'NC',.....);

等等....

于 2012-11-14T06:32:34.467 回答
1

尝试这个:

order by case when `state`='NC' or `state`='North Carolina' then 1 
              when `state`='TN' or `state`='Tennessee' then 2
              when `state`='CO' or `state`='Colorado' then 3
         end 
于 2012-11-14T06:11:12.540 回答
1

您可以结合ORDER BY一个CASE WHEN构造:

ORDER BY CASE 
            WHEN state = 'NC' THEN 1
            WHEN state = 'North Carolina' THEN 2
            ...
         END
于 2012-11-14T06:11:42.710 回答