2009-11-14 50 views
1

我正在处理一些涉及数据库表的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

你能明确什么 “下一步” 和 “上” 是指?是由这个排序暗示...通过插入时间,产品名称的字典顺序,一些任意的用户定义的顺序... – EMPraptor 2009-11-14 06:13:21

+0

@empraptor:好点,对不起,我忘了提及这一点。我检查并且数据应该按照插入的顺序排序。因此,如果产品X在Y之前插入,那么X是Y的前一个。 – Max 2009-11-14 06:30:00

+0

关系数据库作为一般规则是无序表,除非添加了通常无法可靠地告诉订单的人工方法(时间戳列或标识)行被插入。无论如何,为什么插入的订单对最终用户而言是有意义的? – JohnFx 2009-11-14 06:33:09

回答

0

我很困惑....

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

如果输出的页面被戳只,然后从杰夫的回答可以用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

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; 

注意,坏的事情会发生如果你有同名的产品。

+0

不幸的是,这些产品没有命名模式,所以这不是一个选项。是的,它真的很可怕。 – Max 2009-11-14 06:31:09

相关问题