2012-01-25 65 views
0

我需要帶'other'的var_name列在最後,所以我試過了。它的工作原理,但我需要由perc命令第一個選擇語句,UNION不會讓我。無論如何,我確定使用UNION可能是錯誤的。Mysql按例外排序

SELECT count(*) as cnt,(count(*)/$cty)*100 AS perc, var_name 
FROM tbl_answers 
WHERE int_question = $id_question AND var_response <> '' 
AND var_name <> 'comments' AND var_name <> 'Other' 
GROUP BY var_name 
UNION 
SELECT count(*) AS cnt,(count(*)/$cty)*100 as perc,var_name 
FROM tbl_answers 
WHERE int_question = $id_question 
AND var_response <> '' AND var_name <> 'comments' AND var_name = 'Other' 
GROUP BY var_name 

回答

1

你可以使用這個語法

SELECT ....... ORDER BY (var_name = 'Other'), perc 

,因爲MySQL的條件返回0爲假,1爲真,將對其進行排序從VAR_NAME <上升>「其他」以VAR_NAME =「其他」

+0

感謝例子和解釋 – user1083382

0
SELECT count(*) as cnt, (count(*)/$cty)*100 AS perc, var_name 
FROM tbl_answers 
WHERE int_question = $id_question 
AND var_response <> '' 
AND var_name <> 'comments' 
GROUP BY var_name 
ORDER BY (var_name = 'Other') 
     , perc 
0

不要使用工會要做到這一點,只需使用普通的MySQL的ORDER BY:

SELECT count(*) as cnt, (count(*)/$cty)*100 AS perc, var_name 
FROM tbl_answers 
WHERE int_question = $id_question and var_response <> '' AND var_name <> 'comments' 
GROUP BY var_name 
ORDER BY var_name = 'Other'