2012-11-14 107 views
2

我有以下查詢:訂購where條件

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

我需要他們出現在我的where條款(即第一NC,然後TN,然後CO,並依此類推)state訂購的結果。

我該怎麼做?我嘗試使用order by,但它沒有給出這個結果。

回答

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'); 
+0

這僅適用於MySQL是不是?...... – Mortalus

+1

無法看到標籤'MySQL'? –

+2

@Mortalus這個問題有'mysql'標記 –

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 
1

您可以用CASE WHEN結構結合ORDER BY

ORDER BY CASE 
      WHEN state = 'NC' THEN 1 
      WHEN state = 'North Carolina' THEN 2 
      ... 
     END 
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',.....); 

等等....

+0

你應該縮進你的查詢四個空格,以便它會顯示爲代碼 – Chris