您的位置:首页 > 数据库 > MySQL

mysql实现文章上一篇下一篇的sql语句

2015-07-26 00:46 811 查看
转载:http://www.111cn.net/database/mysql/66709.htm

在mysql中查查询上一篇与下一篇只需要对数据进行按id排序之后,然后我们再进行asc或者desc最当前ID下一个就可以了,下面整理了一些例子。

实现网站文章里面上一篇和下一篇的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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: