mysql 1次取出当前记录及上1条下1条记录,效果非常好!
对于让mysql一次取出当前记录,及上1条、下1条,目前网上那条sign( ID - 3 )...的sql语句反正我是看得云里雾里,
自己写了一条比较清晰的sql语句,就是select ... in ( 4 , 5 , 6 )的语句,其中4、5、6通过union连接起来mysql的任务就完成了。然后用php将mysql给出的数据处理一下,ok。
由于才取3条数据, mysql语句怎么union都不会有什么性能问题的。
-------------------------------------------
一次取出编号为7的记录 和 它的上一条、下一条
SELECT * FROM article
where id in(
SELECT max( id ) FROM article WHERE id < 7
union
select 7
union
SELECT min( id ) FROM article WHERE id > 7
)
结果::
技术细节见下:
1.article表结构: aid( 主键 ) title content ... ,
2.sql语句,
3.php执行和处理 .
$sql = "
SELECT * FROM article
where
`aid` in(
SELECT max( `aid` ) FROM article WHERE `aid` < {$id}
union all
SELECT {$id}
union all
SELECT min( `aid` ) FROM article WHERE `aid` > {$id}
)
ORDER BY aid ASC
LIMIT 0,3
";
$list = db::get_all( $sql );
empty( $list ) && exit( '该文章不存在.' );
//再次遍历,判断文章编号是否存在.
$aid_exists = false;
$row = array();
foreach ( $list as $n=>$line ){
if ( $id == $line['aid'] ){
$aid_exists = true;
$row = $line; //当前记录
break;
}
}
false === $aid_exists && exit( '该文章不存在.' );
//它的后1条
$row['prev'] = isset( $list[$n-1] ) ? $list[$n-1] : false;
//它的前1条
$row['next'] = isset( $list[$n+1] ) ? $list[$n+1] : false;
// 载入show.html模版
tpl( 'show' , $row );
?>
上述得到$row的结构:: (黄色背景色是当前的数据,prev next分别是上1条、下1条)
$row = Array(
[aid] => 5
[title] =>叶斯算法(bayesian)介绍
[prev] => Array(
[aid] => 4
[title] => ffffffffff
)
[next] => Array (
[aid] => 6
[title] =>模式四要素
)
)
----------------
再在show.html里面写上如下代码::
#prev_next span{ display: inline-block; width: 260px ; }
<下一篇:
if( $next ) {
$next_short = substr( $next['content'] , 0 , 150 );
echo "".substr( $next['title'] , 0 , 30 ).'';
}
else{
echo '没有了';
}
?>
上一篇:
if( $prev ) {
$prev_short = substr( $prev['content'] , 0 , 150 );
echo "".substr( $prev['title'] , 0 , 30 ).'';
}
else{
echo '没有了';
}
?>
>
结果是相当满意,如下图::
性能分析::
explain一下上面那条语句:
使用了key: PRIMARY 主键 作为索引,所以性能是可以的.