如何在数据库中找到下一行/上一行?

时间:2009-11-14 06:04:58

标签: mysql

我正在开发一些涉及数据库表的PHP / mysql 5 Web项目,该数据库表使用非索引的GUID字符串作为行的标识符。因此,此产品表的行如下所示:

GUID                                   Name
936DA01F-9ABD-4d9d-80C7-02AF85C822A8   Product 1
07c5bcdc-b3a6-482f-8556-bb04fae06538   Product 2
b7b39700-d0e2-11de-8a39-0800200c9a66   Product 3

新要求是,当我在Product 2的详细信息页面上时,此页面应包含以前的链接(指向Product 1)和指向Product 3的反向链接。

查找Product 2非常简单:

SELECT * FROM products WHERE GUID = "07c5bcdc-b3a6-482f-8556-bb04fae06538"

但是如何找到上一个和下一个产品的GUID?

请记住:产品表没有自动增量列,我无法轻松添加,因为我无法控制数据库......

修改

记录按时间戳列排序。

3 个答案:

答案 0 :(得分:1)

哇,太可怕了。

这样的事情会起作用吗?这是假设您按名称对产品进行排序。

如果您在产品2页面上...

获得产品1:

select guid from product where name < 'Product 2' order by name desc limit 1;

获得产品3:

select guid from product where name > 'Product 2' order by name asc limit 1;

请注意,如果您的商品名称相同,则会发生不良事件。

答案 1 :(得分:0)

行ID有助于......

我找到了这个链接:http://forums.mysql.com/read.php?61,25654,173160#msg-173160

set @a := 0;
select *, @a := @a+1 as rowid
from table
limit 10 ;

答案 2 :(得分:0)

我很困惑....

关于杰夫的回答;如果产品没有命名方案(随机?) 产品如何在输出中排序到页面?

如果页面的输出仅按时间戳排序,那么Jeff的答案可以与where子句的一个小改动一起使用:

select guid from product
where timestamp < (select timestamp from product where name = 'Product 2')
order by timestamp desc limit 1;

和另一个:

select guid from product
where timestamp > (select timestamp from product where name = 'Product 2')
order by timestamp asc limit 1;


或者使用“产品2”中的GUID:

select guid from product
where timestamp < (select timestamp from product where GUID = guid_from_product2)
order by timestamp desc limit 1;

和另一个:

select guid from product
where timestamp > (select timestamp from product where guid = guid_from_product2)
order by timestamp asc limit 1;

问候
Sigersted

相关问题