1. 前言
最近升級博客,給文章頁面底部增加了兩個按鈕,可以直接跳轉到上一篇和下一篇。
如下圖所示:
實現這個功能的難點在于:數據庫怎么選取出一條記錄的前后兩條相鄰的記錄?
2. 數據庫設計
關于我文章數據庫的設計如下圖所示:
可以看到,每條記錄的身份是索引Id。因為之前有很多文章記錄被刪除了,所以,Id并不是連續的。
如果當前文章的索引值是33,那么可以通過以下命令來得到前后相鄰的 2 篇文章:
select * from passage where id in(selectcasewhen SIGN(id - 32 )>0 THEN MIN(id)when SIGN(id - 32 )<0 THEN MAX(id)endfrom passagewhere id != 34GROUP 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 5.7.5后only_full_group_by成為sql_mode的默認選項之一,這可能導致一些sql語句失效。
進入 mysql 配置文件,在[mysqld]部分中添加以下配置,并且重啟 mysql 即可。
[mysqld]# ... other configsql_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. 相關鏈接
only_full_group_by
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答