mysql怎么在非ID列排序的情况下取出某个ID之后的数据

suifengJC614 2016-12-15 09:08:04
例子如下
现有表如下
id num
1 3
2 1
3 2
4 2
5 3
6 2
7 1
要求排序规则为 order by num desc, id desc
在这个排序规则之下找出某个ID之后的数据,包括指定的这个ID,输入条件只有这个ID

假如现在输入ID 为 4 那么相应输出结果应该为
id num
4 2
3 2
7 1
2 1

假如现在输入ID 为 1 那么相应输出结果应该为
id num
1 3
6 2
4 2
3 2
7 1
2 1


我尝试过limit 但是问题是现在输入条件只有ID 我无法找出这个ID对应应该limit 的 偏移量
我也尝试过用模拟rownum的办法取出,使用子查询,但是貌似limit 后面不能跟子查询?
我尝试后报错
希望各位大神能给出mysql的查询语句,小弟不胜感激
...全文
497 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
gzcitizeny 2016-12-19
  • 打赏
  • 举报
回复
不知这样能否运行: select * from tb where num<(select num from tb where id=xxx) or (num=(select num from tb where id=xxx) and id<=xxx) order by num desc, id desc
ACMAIN_CHM 2016-12-17
  • 打赏
  • 举报
回复
order by id=@id desc, num desc, id desc
rucypli 2016-12-16
  • 打赏
  • 举报
回复
select * from tb where num <= (select max(num) from tb where id=xxx)
suifengJC614 2016-12-16
  • 打赏
  • 举报
回复
引用 1 楼 rucypli 的回复:
select * from tb where num <= (select max(num) from tb where id=xxx)
这个不行啊 num有重复值,这样会把与num相等的都查出来 例如上面的例子中 输入ID 为 4的哪个结果,num=2的 ID为6的数据是不在输出结果里的
suifengJC614 2016-12-16
  • 打赏
  • 举报
回复
引用 2 楼 gzcitizeny 的回复:
根据1楼做些改动: select * from tb where num <= (select num from tb where id=xxx) order by num desc, id desc
你好,你这个跟1楼的一样,可能没注意我这里的要求 以上面例子为例 select num from tb where id=4 那么查出来的num 为 2 这样num<=2的条件里面 是包含ID大于4的结果的
suifengJC614 2016-12-16
  • 打赏
  • 举报
回复
引用 1 楼 rucypli 的回复:
select * from tb where num <= (select max(num) from tb where id=xxx)
这个不行啊 num有重复值,这样会把与num相等的都查出来 例如上面的李忠 输入ID 为 4的哪个结果,num=2的 ID为5的数据是不在输出结果里的
gzcitizeny 2016-12-16
  • 打赏
  • 举报
回复
根据1楼做些改动: select * from tb where num <= (select num from tb where id=xxx) order by num desc, id desc

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧