1. 程式人生 > >MySQL: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sss

MySQL: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sss

今天在執行MySQL中sql語句的時候報錯了,執行的sql語句:

SELECT
    prov_desc,
    area_desc,
    month_id,
    MAX(total_fee)AS max_total,
FROM
sss
WHERE
    prov_id = '075'
OR prov_id IN('017')
AND month_id IN('201207')
GROUP BY
    prov_id,
    prov_desc,
    prov_ord,
    area_desc,
    area_ord
HAVING
    MAX(total_fee)> 100
ORDER BY prov_ord DESC, area_ord

錯誤提示如下:

Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sss.month_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

​ 認真看錯誤的提示發現是在group by中的欄位比較selelct中的欄位差了一個month_id, 而正好是month_id報錯。this is incompatible with sql_mode=only_full_group_by

這句話提示了這違背了mysql的規則,only fully group by,也就是說在執行的時候先分組,根據查詢的欄位(select的欄位)在分組的內容中取出,所以查詢的欄位全部都應該在group by分組條件內;一種情況例外,查詢欄位中如果含有聚合函式的欄位不用包含在group by中,就像我上面的MAX(total_fee),至於為什麼,我也不擡明白。
​ 後來發現Order by排序條件的欄位也必須要在group by內,看此大神的博文解釋之後豁然開朗,排序的欄位也是從分組的欄位中取出。 不明白的可以去看一下。

解決辦法:select欄位必須都在group by分組條件內(含有函式的欄位除外)。(如果遇到order by也出現這個問題,同理,order by欄位也都要在group by內)。