日期:2014-05-16 浏览次数:21055 次
select A.* from test A,test B where B.id=4 and A.timedate<=B.timedate order by A.timedate desc,A.id desc limit 1,1
------解决方案--------------------
你要物理顺序,插入有自增字段的临时表 OR 用变量解决
------解决方案--------------------
set @iid := 0; drop table if exists tmp_t; -- 如果使用临时表则不能自连接,可以创建两个临时表来处理,或是如此示例使用物理表,最后删除“临时”用的“物理”表 create table tmp_t select @iid:=@iid+1 as iid, xxx.* from Test order by timedate desc, id desc; select t2.id, t2.timedate from tmp_t as t1 left join tmp_t as t2 on t1.iid = t2.iid - 1 where t1.id = [指定的ID]; -- 执行 drop table if exists tmp_t;
------解决方案--------------------
mysql> select * from test;
+------+---------------------+
| id | timedate |
+------+---------------------+
| 1 | 2011-07-11 00:00:00 |
| 2 | 2011-06-11 00:00:00 |
| 3 | 2011-06-11 00:00:00 |
| 4 | 2011-06-11 00:00:00 |
| 5 | 2011-09-11 00:00:00 |
| 6 | 2011-05-11 00:00:00 |
+------+---------------------+
6 rows in set (0.00 sec)
mysql> select * from test
-> where timedate<(select timedate from Test where id=4)
-> or (timedate=(select timedate from Test where id=4) and id <4)
-> order by timedate desc,id desc
-> limit 1;
+------+---------------------+
| id | timedate |
+------+---------------------+
| 3 | 2011-06-11 00:00:00 |
+------+---------------------+
1 row in set (0.00 sec)
mysql> select * from test
-> where timedate<(select timedate from Test where id=3)
-> or (timedate=(select timedate from Test where id=3) and id <3)
-> order by timedate desc,id desc
-> limit 1;
+------+---------------------+
| id | timedate |
+------+---------------------+
| 2 | 2011-06-11 00:00:00 |
+------+---------------------+
1 row in set (0.00 sec)
mysql> select * from test
-> where timedate<(select timedate from Test where id=2)
-> or (timedate=(select timedate from Test where id=2) and id <2)
-> order by timedate desc,id desc
-> limit 1;
+------+---------------------+
| id | timedate |
+------+---------------------+
| 6 | 2011-05-11 00:00:00 |
+------+---------------------+
1 row in set (0.00 sec)
mysql>