sql按token分页查询加额外排序条件

有些查询场景需要分页,但是用的不是limit offset实现的,用的是id > last_id.

语句如下, 这种查询可以满足分页需求。

select * from table where id > last id order by id asc limit 10;

但是有的时候希望按创建时间排序,如果直接用下面的语句有问题,因为无法严格保证create_at和id大小完全一致(id是用id生成器生成的,然后结合业务逻辑写数据库的,不严格有序)。

select * from table where id > last_id order by id asc,created_at asc limit 10;

可能产生第二页的时间比第一页更早,不符合需求。

select * from table where id > last_id order by created_at asc,id asc limit 10;

有些数据会漏查


解决方案:

select  * from table where created_at > last_create_at or (created_at = last_create_at and id > last_id ) order by created_at asc, id asc;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容