mysql實現文章上一篇下一篇的sql語句

來源:互聯網
上載者:User

實現網站文章裡面上一篇和下一篇的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);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.