實現網站文章裡面上一篇和下一篇的sql語句的寫法。
當前文章的id為 $article_id,當前文章對應分類的id是$cat_id,那麼上一篇就應該是:
| 代碼如下 |
複製代碼 |
SELECT max(article_id) FROM article WHERE article_id < $article_id AND cat_id=$cat_id; 執行這段sql語句後得到 $max_id,然後 SELECT article_id, title FROM article WHERE article_id = $max_id; 簡化一下,轉為子查詢即: SELECT article_id, title FROM article WHERE article_id = (SELECT max(article_id) FROM article WHERE article_id < $article_id AND cat_id=$cat_id); |
下一篇為:
| 代碼如下 |
複製代碼 |
SELECT min(article_id) FROM article WHERE article_id > $article_id AND cat_id=$cat_id; 執行這段sql語句後得到 $min_id,然後 SELECT article_id, title FROM article WHERE article_id = $min_id; |
簡化一下,轉為子查詢即:
| 代碼如下 |
複製代碼 |
SELECT article_id, title FROM article WHERE article_id = (SELECT min(article_id) FROM article WHERE article_id > $article_id AND cat_id=$cat_id); |
最後講一下有很多朋友喜歡使用下面語句
上一篇:
| 代碼如下 |
複製代碼 |
select id from table where id<10 order by id desc limit 0,1; 下一篇: select id from table where id>10 limit 0,1; |
這樣肯定沒有問題,但是是效能感覺不怎麼地。
sql語句最佳化
你可以使用union all來實現一條語句取3行資料,但是前提是3個查詢的欄位要相同
這個查詢出來的結果第一行就是上一篇文章,第二行是當前文章,第三行是下一篇文章
| 代碼如下 |
複製代碼 |
(select id from table where id < 10 order by id asc limit 1) union all (select id from table where id = 10) union all (select id from table where id > 10 order by id desc limit 1); |