Mysql按异常排序

时间:2012-01-25 13:15:27

标签: mysql

我需要带有'other'的var_name列在最后,所以我尝试了这个。它工作但我需要通过perc订购第一个select语句,UNION不会让我。我确定使用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
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

3 个答案:

答案 0 :(得分:1)

您可以使用此语法

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

因为MySQL中的条件将0返回为false,将1返回为true,它将从var_name&lt;&gt;中提升它。 “其他”到var_name ='其他'

答案 1 :(得分: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

答案 2 :(得分: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'