国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > MySQL > 正文

Mysql升級到5.7后遇到的group by查詢問題解決

2024-07-24 12:51:10
字體:
供稿:網(wǎng)友

發(fā)現(xiàn)問題

最近在將mysql升級到mysql 5.7后,進行一些group by 查詢時,比如下面的

SELECT *, count(id) as count FROM `news` GROUP BY `group_id` ORDER BY `inputtime` DESC LIMIT 20

就會報如下錯誤:

SELECT list is not in GROUP BY clause and contains nonaggregated column ‘news.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by.

原因分析

原因是mysql 5.7 模式中。默認啟用了ONLY_FULL_GROUP_BY。

ONLY_FULL_GROUP_BY是MySQL提供的一個sql_mode,通過這個sql_mode來提供SQL語句GROUP BY合法性的檢查。

http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_only_full_group_by

this is incompatible with sql_mode=only_full_group_by這句話提示了這違背了mysql的規(guī)則,only fully group by,也就是說在執(zhí)行的時候先分組,根據(jù)查詢的字段(select的字段)在分組的內(nèi)容中取出,所以查詢的字段全部都應該在group by分組條件內(nèi);一種情況例外,查詢字段中如果含有聚合函數(shù)的字段不用包含在group by中,就像我上面的count(id)。

后來發(fā)現(xiàn)Order by排序條件的字段也必須要在group by內(nèi),排序的字段也是從分組的字段中取出。 不明白的可以去看一下。

解決辦法:

1.set@@sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

去掉ONLY_FULL_GROUP_BY即可正常執(zhí)行sql.

2. 不去ONLY_FULL_GROUP_BY, 時 select字段必須都在group by分組條件內(nèi)(含有函數(shù)的字段除外)。(如果遇到order by也出現(xiàn)這個問題,同理,order by字段也都要在group by內(nèi))。

3.利用ANY_VALUE()這個函數(shù) https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value

This function is useful for GROUP BY queries when the ONLY_FULL_GROUP_BY SQL mode is enabled, for cases when MySQL rejects a query that you know is valid for reasons that MySQL cannot determine. The function return value and type are the same as the return value and type of its argument, but the function result is not checked for the ONLY_FULL_GROUP_BY SQL mode.

如上面的sql語句可寫成

SELECT ANY_VALUE(id)as id,ANY_VALUE(uid) as uid ,ANY_VALUE(username) as username,ANY_VALUE(title) as title,ANY_VALUE(author) as author,ANY_VALUE(thumb) as thumb,ANY_VALUE(description) as description,ANY_VALUE(content) as content,ANY_VALUE(linkurl) as linkurl,ANY_VALUE(url) as url,ANY_VALUE(group_id) as group_id,ANY_VALUE(inputtime) as inputtime, count(id) as count FROM `news` GROUP BY `group_id` ORDER BY ANY_VALUE(inputtime) DESC LIMIT 20

我選用的是第3種方法。

總結

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對錯新站長站的支持。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 七台河市| 镇江市| 长寿区| 遂平县| 泽库县| 崇文区| 江北区| 西乌珠穆沁旗| 大英县| 西宁市| 吴川市| 洛南县| 聊城市| 黔江区| 大丰市| 云浮市| 三门县| 台东市| 获嘉县| 黄山市| 上思县| 冀州市| 衡阳市| 定日县| 土默特左旗| 乃东县| 贵阳市| 保山市| 雅江县| 嘉禾县| 襄城县| 太谷县| 化隆| 旺苍县| 彰化市| 县级市| 客服| 瑞昌市| 榆林市| 武山县| 汉阴县|