mysql查询按时间排序,指定id后返回n行

zy1mlcev  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(217)

我的数据库中有一个表(版本:mariadb 10.3.17,mysql 5.7),如下所示:

id      name        timestamp
-----------------------------
154875  AXC         154875869
362574  RTB         154875800
962548  MNV         154875969
365847  XRT         154875123
...

我需要的是:
按时间戳降序排列行
然后在id=something的后面(下面)返回24行
例如,对于id=962548,预期输出的前3行是:

id      name        timestamp
-----------------------------
154875  AXC         154875869
362574  RTB         154875800
365847  XRT         154875123

如何在mysql中实现?

mcvgt66p

mcvgt66p1#

在您的条件下,将返回id=something的行的查询联接到表中:

select t.*
from tablename t 
inner join (select * from tablename where id = 365847) c
on t.timestamp < c.timestamp or (t.timestamp = c.timestamp and t.id < c.id)
order by t.timestamp desc, t.id desc
limit 24

但我不知道你下面说的是什么意思,所以也许你想要相反的顺序:

select t.*
from tablename t 
inner join (select * from tablename where id = 365847) c
on t.timestamp > c.timestamp or (t.timestamp = c.timestamp and t.id > c.id)
order by t.timestamp desc, t.id desc
limit 24
rjjhvcjd

rjjhvcjd2#

您需要使用如下查询选择时间戳值大于id时间戳的元素:

SELECT * 
FROM table 
WHERE timestamp>(select timestamp 
                 from table
                 where id = 'current_id') 
ORDER BY timestamp LIMIT 24;
pgky5nke

pgky5nke3#

我会这样问:

SELECT * FROM tab
WHERE timestamp >= (SELECT timestamp FROM tab WHERE id = 154875)
AND id <> 154875
ORDER BY timestamp DESC,  id DESC
LIMIT 2

相关问题