mongodb和mysql查询当前记录的上一条和下一条

思路:根据当前记录的id查询先后记录。mysql

mongodb实现方法:

mongo能够经过时间或者经过id来判断上一条记录或者下一条记录:sql

经过记录的_id

上一条记录mongodb

db.数据库名称.find({ '_id': { '$lt': ids } }).sort({_id: -1}).limit(1)

下一条记录数据库

db.数据库名称.find({ '_id': { '$gt': ids } }).sort({_id: 1}).limit(1)

经过时间字段来查询:

上一条记录code

db.数据库名称.find({ 'created': { '$lt': created } }).sort({_id: -1}).limit(1)

下一条记录it

db.数据库名称.find({ 'created': { '$gt': created } }).sort({_id: 1}).limit(1)

mysql实现方法:

mysql查询,网上有不少方法,一般咱们用以下方法:io

查询上一条记录的SQL语句(若是有其余的查询条件记得加上other_conditions以避免出现没必要要的错误):table

select * from table_a 
    where id = 
        (select id from 
            table_a where id < {$id} [and other_conditions] 
            order by id desc limit 1
        ) 
   [and other_conditions];

查询下一条记录的SQL语句(若是有其余的查询条件记得加上other_conditions以避免出现没必要要的错误):select

select * from table_a 
    where id = 
        (select id from table_a 
            where id > {$id} [and other_conditions] 
            order by id asc limit 1
        ) 
    [and other_conditions];
相关文章
相关标签/搜索