这就是我用来查找上一个/下一个记录的方法。表格中的任何列都可以用作排序列,并且不需要联接或讨厌的技巧:
下一条记录(日期大于当前记录):
SELECt id, title, MIN(created) AS created_dateFROM photoWHERe created > (SELECt created FROM photo WHERe id = '32kJ')GROUP BY createdORDER BY created ASCLIMIT 1;
上一个记录(日期小于当前记录):
SELECt id, title, MAX(created) AS created_dateFROM photoWHERe created < (SELECt created FROM photo WHERe id = '32kJ')GROUP BY createdORDER BY created DESCLIMIT 1;
例:
CREATE TABLE `photo` ( `id` VARCHAr(5) NOT NULL, `title` VARCHAr(255) NOT NULL, `created` DATETIME NOT NULL, INDEX `created` (`created` ASC), PRIMARY KEY (`id`))ENGINE = InnoDB;INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('XEi43', 'my family', '2009-08-04');INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('dDls', 'friends group', '2009-08-05');INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('32kJ', 'beautiful place', '2009-08-06');INSERT INTO `photo` (`id`, `title`, `created`) VALUES ('EOIk', 'working late', '2009-08-07');SELECt * FROM photo ORDER BY created;+-------+-----------------+---------------------+| id | title| created |+-------+-----------------+---------------------+| XEi43 | my family | 2009-08-04 00:00:00 || dDls | friends group | 2009-08-05 00:00:00 || 32kJ | beautiful place | 2009-08-06 00:00:00 || EOIk | working late | 2009-08-07 00:00:00 |+-------+-----------------+---------------------+SELECt id, title, MIN(created) AS next_dateFROM photoWHERe created > (SELECt created FROM photo WHERe id = '32kJ')GROUP BY createdORDER BY created ASCLIMIT 1;+------+--------------+---------------------+| id | title | next_date|+------+--------------+---------------------+| EOIk | working late | 2009-08-07 00:00:00 |+------+--------------+---------------------+SELECt id, title, MAX(created) AS prev_dateFROM photoWHERe created < (SELECt created FROM photo WHERe id = '32kJ')GROUP BY createdORDER BY created DESCLIMIT 1;+------+---------------+---------------------+| id | title | prev_date|+------+---------------+---------------------+| dDls | friends group | 2009-08-05 00:00:00 |+------+---------------+---------------------+
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)