MySQL根据listorder的id顺序获取上一条和下一条记录

时间:2014-04-25 06:42:51

标签: mysql

我尝试使用php和mysql创建下一个和上一个导航。我的问题是我无法使其发挥作用。这是我到目前为止所做的:

查询:

select * from blog_entry where deleted='n' and isDisplayed='y' and b_id = (select max(b_id) from blog_entry where deleted='n' and isDisplayed='y' and b_id < 154) order by listorder desc

表格

enter image description here

所以在我的页面中,如果我在条目号154(b_id:154)上,单击下一个按钮将显示来自b_id 152的内容,与之前的记录相同。提前致谢! :)

3 个答案:

答案 0 :(得分:0)

以下查询将为您提供记录no 153

select * from blog_entry where deleted='n' and isDisplayed='y' and b_id = (select max(b_id) from blog_entry where deleted='n' and isDisplayed='y' and b_id < 154) order by listorder desc limit 1

以下查询将为您提供第155号记录

select * from blog_entry where deleted='n' and isDisplayed='y' and b_id = (select max(b_id) from blog_entry where deleted='n' and isDisplayed='y' and b_id > 154) order by listorder  limit 1

答案 1 :(得分:0)

使用此

select * from `blog_entry` where `deleted`='n' and `isDisplayed`='y' order by `b_id` desc limit 1,1

答案 2 :(得分:0)

您可以在阅读blog_entries的原始选择中执行一半。其他解决方案每行需要2个额外的选择,这是更多。另一半(存储&#34;下一个&#34;)我会在阅读所选值后在php中做。

请注意选择字段的正确顺序:

set @last_id=null;

select * from 
(
    select @last_id as last_id, (@last_id := b.id) as id, b.listorder, b.<content>
    from blog_entry b where deleted='n' and isDisplayed='y'
    order by b.id
) as tech_subsel
order by listorder;

编辑:php-part

$result = array();

while ($row = <read row>){
    if(isset($result[$row['last_id']]){
          $result[$row['last_id']]['next_id'] = $row['id'];
    }
    $result[$row['id']] = $row;
}

然后你在一次扫描中有last_id和next_id。