Mysql無法選取非聚合列

教程所示圖片使用的是 github 倉庫圖片,網速過慢的朋友請移步>>> (原文)Mysql 無法選取非聚合列

更多討論或者錯誤提交,也請移步。

1. 前言

最近升級博客,給文章頁面底部增加了兩個按鈕,可以直接跳轉到上一篇和下一篇。如下圖所示:
效果圖

實現這個功能的難點在於:數據庫怎麼選取出一條記錄的前後兩條相鄰的記錄?

2. 數據庫設計

關於我文章數據庫的設計如下圖所示:
數據庫設計

可以看到,每條記錄的身份是索引Id。因爲之前有很多文章記錄被刪除了,所以,Id並不是連續的。

如果當前文章的索引值是33,那麼可以通過以下命令來得到前後相鄰的 2 篇文章:

select * from passage where id in
(select
case
when SIGN(id - 32 )>0 THEN MIN(id)
when SIGN(id - 32 )<0 THEN MAX(id)
end
from passage
where id != 34
GROUP BY SIGN(id- 32 )
ORDER BY SIGN(id- 32 )
)
ORDER BY id;

3. 無法選取聚合列

在執行上面命令時,Mysql給了我個: SELECT list is not in GROUP BY clause ... 的報錯。經過 Google 得知,mysql 5.7以上,默認啓動了only_full_group_by,MySQL 就會拒絕選擇列表、條件或順序列表引用的查詢。

以下是原文:

Reject queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on (uniquely determined by) GROUP BY columns.
As of MySQL 5.7.5, the default SQL mode includes ONLY_FULL_GROUP_BY. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default. For a description of pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)

所以,我們應該設置sql_mode不包含only_full_group_by選項

進入 mysql 配置文件,在[mysqld]部分中添加以下配置,並且重啓 mysql 即可。

[mysqld]
# ... other config
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATEERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION # delete 'only_full_group_by'
# ... other config

運行本文第二部分的 mysql 的命令,結果如下圖所示:
運行結果

4. 相關鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章