select * from table_a where id = (select id from table_a where id < {$id} order by id desc limit 1); select * from table_a where id = (select id from table_a where id > {$id} order by id asc limit 1);
方法2:
select * from table_a where id = (select max(id) from table_a where id < {$id}); select * from table_a where id = (select min(id) from table_a where id > {$id});
select * from `dxc_blog` where `id` between (select `id` from `dxc_blog` where `id` < '5' order by `id` desc limit 1) and (select `id` from `dxc_blog` where `id` > '5' order by `id` asc limit 1);
发布评论
评论(5)
这样?
select * from table where id>$id order by id asc limit 1;
select * from table where id<$id order by id desc limit 1;
如果ID是主键或者有索引,可以直接查找:
方法1:
select * from table_a where id = (select id from table_a where id < {$id} order by id desc limit 1);
select * from table_a where id = (select id from table_a where id > {$id} order by id asc limit 1);
方法2:
select * from table_a where id = (select max(id) from table_a where id < {$id});
select * from table_a where id = (select min(id) from table_a where id > {$id});
其他更优的暂时还没想出来
数据结构设置为双向链表的形式:
id,preId,nextId,otherData
在删除某id时,更新上一条和下一条的链接关系就行了吧?
补充个PHP的例子:
<?php
// 新建
$data = new Data;
$data->otherData = "我家本住在,苏州~的城边~";
$data->id = $db->create($data);
// 只在新建时,有个order by的查询,其他sql都是直接id定位
$preId = $db->read("id<{$data->id} order by id desc limit 1");
$db->update("set preId={$preId} where id={$data->id}");
$db->update("set nextId={$data->id} where id={$preId}");
?>
<?php
// 查询和显示
$data = $db->read("id=9527");
echo $data->otherData;
echo "[link id={$data->preId}]上一条[/link] ";
echo "[link id={$data->nextId}]下一条[/link]";
?>
<?php
// 删除
$data = $db->read("id=9527");
$db->update("set nextId={$data->nextId} where id={$data->preId}");
$db->update("set preId={$data->preId} where id={$data->nextId}");
$db->delete($data->id);
?>
我想要实现“高效的提取”,莫过于一次读取3条记录(上一条、当前、下一条),因为读取磁盘或内存连续空间速度很快。所以你可以参照如下伪SQL语句:
select top 3 where id>=((select id where xxx=yyyy)-1) order by id asc
“select id where xxx=yyyy”为“SQL查询的当前数据”。另外,对“ID不连续”的情况也适用。
表里有ID为3,5,6的顺序记录(ID不连续),以下sql测试成功:
select * from `dxc_blog` where `id` between
(select `id` from `dxc_blog` where `id` < '5' order by `id` desc limit 1)
and
(select `id` from `dxc_blog` where `id` > '5' order by `id` asc limit 1);