mysql逐条取出使用_mysql in(...) 1次取出当前记录及上1条下1条记录, 且使用了主键作为索引...

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

)

结果::

da5b25ede6667d5ddda353370381da3a.png

技术细节见下:

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 '没有了';

}

?>

>

结果是相当满意,如下图::

1273250a167622360aad7d30d92365dc.png

性能分析::

explain一下上面那条语句:

使用了key: PRIMARY 主键 作为索引,所以性能是可以的.

84f412a1af8f69f17dbc5027acd47142.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值