mysql 根據某欄位去重時遇到的問題
需要根據某個欄位進行去重,但是會報錯,
Expression #1 of ORDER BY clause is not in SELECT list, references column 'a.time' which is not in SELECT list; this is incompatible with DISTINCT
SELECT list is not in GROUP BY clause and contains nonaggregated column ‘a.time' which is not functionally dependent on columns in GROUP BY clause; this is incompatible withsql_mode=only_full_group_by
第一條報錯是使用了DISTINCT,第二條報錯是使用了group by去重
百度上去找原因,都是在說由於mysql5.7.5及以上版本實現了對功能依賴的檢測。預設啟用了ONLY_FULL_GROUP_BY SQL模式
需要修改
set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
但是我執行力之後無效,而且我查詢sql_mode中並沒有only_full_group_by,原因未知
於是嘗試了第二種方法,在報錯欄位上面加ANY_VALUE(),問題解決
原sql:
select Id,time from
(SELECT a.xxx Id,a.time
from xxxx join xxxxx where xxxxxx
) a group by Id order bya.time desc limit 0,10;
新sql:
select ANY_VALUE(Id),ANY_VALUE(time) from
(SELECT a.xxx Id,a.time
from xxxx join xxxxx where xxxxxx
) a group by Id order by ANY_VALUE
ANY_VALUE這個函式好像只有在5.7版本以上才有