求sql语句一条
表:table 下面是数据格式
id loid isdefault
1 08009 0
2 08010 0
3 08011 0
4 08012 1
5 08013 0
6 08014 0
.
.
.
.
其中isdefault中只能用一个是1,其它的均为0
我想用一条语句得到isdefault=1的loid的后面所有数据,如果isdefault=1后面的数据不够10条就用前面的数据补齐。一般情况下isdefault=1后面的数据都不会超过4条。
表:table 下面是数据格式
id loid isdefault
1 08009 0
2 08010 0
3 08011 0
4 08012 1
5 08013 0
6 08014 0
.
.
.
.
其中isdefault中只能用一个是1,其它的均为0
我想用一条语句得到isdefault=1的loid的后面所有数据,如果isdefault=1后面的数据不够10条就用前面的数据补齐。一般情况下isdefault=1后面的数据都不会超过4条。
怎么计算,以ID大小?
好好想想 很简单的逻辑!
第一种方法:
一条sql,数据量比较小时,无所谓,当比较大时,建议用下面的2条sql实现。
select * from table where isdefault !=1 order by case when id > (select id from table where isdefault = 1 ) then 0 else 1 end , id limit 10第二种方法:
两条sql:
第一:查询 isdefault = 1 的条记录对应的id
第二:
select * from table where isdefault !=1 order by case when id > 刚才查询出来的id then 0 else 1 end , id limit 10楼主看懂了以后,可以按照实际需要改写。select * from table where isdefault !=1 order by case when id > (select id from table where isdefault = 1 ) then 0 else 1 end asc , id asc limit 10等等,如果不是用id排序,可以这样改:
select * from table where isdefault !=1 order by case when id > (select id from table where isdefault = 1 ) then 0 else 1 end asc , 我要的排序字段 asc/desc limit 10
select a.* from ttr a
left join
(select id from ttr where isdefault1=1) b
on a.id>b.id where b.id is not null
union
select * from ttr where isdefault1<>1) a limit 10