这个mysql查询语句怎么写?
时间:2011-12-26
来源:互联网
表Test结构为两个字段,id与timedate,id为自动增长,timedate为时间,id唯一,时间,有可能会相同,也有可能为空。
现已知id值,我要通过id查询一条记录,查询规则为按时间降序,id降序的下一条记录,
select * from Test order by timedate desc,id desc 即按条语句查询结果,找出该id所在记录的下一条记录。
测试数据如下:
id timedate
1 2011-7-11 0:00:00
2 2011-6-11 0:00:00
3 2011-6-11 0:00:00
4 2011-6-11 0:00:00
5 2011-9-11 0:00:00
6 2011-5-11 0:00:00
通过select * from Test order by timedate desc,id desc 排序后:
id timedate
5 2011-9-11 0:00:00
1 2011-7-11 0:00:00
4 2011-6-11 0:00:00
3 2011-6-11 0:00:00
2 2011-6-11 0:00:00
6 2011-5-11 0:00:00
现在我想实现的是这样的:
如果id=4,那么,我想查到id=3这条记录,
如果id=3,那么,我想查到id=2这条记录,
如果id=2,那么,我想查到id=6这条记录
该怎么写呢?下面这样写不行:select * from Test where id = 4 and timedate <= (select timedate from Test where id=4)
在mssql已开了一贴,mssql有人写出来了,但mysql的,还是不对,来这边再问一次吧。
原贴:http://topic.csdn.net/u/20111226/14/f8928731-4951-45e2-8e13-c563bdc095e1.html?seed=1234716279&r=77079730#r_77079730
现已知id值,我要通过id查询一条记录,查询规则为按时间降序,id降序的下一条记录,
select * from Test order by timedate desc,id desc 即按条语句查询结果,找出该id所在记录的下一条记录。
测试数据如下:
id timedate
1 2011-7-11 0:00:00
2 2011-6-11 0:00:00
3 2011-6-11 0:00:00
4 2011-6-11 0:00:00
5 2011-9-11 0:00:00
6 2011-5-11 0:00:00
通过select * from Test order by timedate desc,id desc 排序后:
id timedate
5 2011-9-11 0:00:00
1 2011-7-11 0:00:00
4 2011-6-11 0:00:00
3 2011-6-11 0:00:00
2 2011-6-11 0:00:00
6 2011-5-11 0:00:00
现在我想实现的是这样的:
如果id=4,那么,我想查到id=3这条记录,
如果id=3,那么,我想查到id=2这条记录,
如果id=2,那么,我想查到id=6这条记录
该怎么写呢?下面这样写不行:select * from Test where id = 4 and timedate <= (select timedate from Test where id=4)
在mssql已开了一贴,mssql有人写出来了,但mysql的,还是不对,来这边再问一次吧。
原贴:http://topic.csdn.net/u/20111226/14/f8928731-4951-45e2-8e13-c563bdc095e1.html?seed=1234716279&r=77079730#r_77079730
作者: xzy88 发布时间: 2011-12-26
SQL code
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
作者: rucypli 发布时间: 2011-12-26
引用 1 楼 rucypli 的回复:
SQL code
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
SQL code
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
不对呀,当id=3的时候,结果就不对了。。。。
作者: xzy88 发布时间: 2011-12-26
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28