Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL查询按时间排序,在指定id后返回n行_Mysql_Sql_Database_Mariadb - Fatal编程技术网

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

MySQL查询按时间排序,在指定id后返回n行,mysql,sql,database,mariadb,Mysql,Sql,Database,Mariadb,我的数据库版本中有一个表:MariaDB 10.3.17,MySQL 5.7,如下所示: id name timestamp ----------------------------- 154875 AXC 154875869 362574 RTB 154875800 962548 MNV 154875969 365847 XRT 154875123 ... 我需要的是: 按时间戳降序对行进行排序

我的数据库版本中有一个表:MariaDB 10.3.17,MySQL 5.7,如下所示:

id      name        timestamp
-----------------------------
154875  AXC         154875869
362574  RTB         154875800
962548  MNV         154875969
365847  XRT         154875123
...
我需要的是:

按时间戳降序对行进行排序 然后返回下面的24行,其中id=something 例如,对于id=962548,预期输出的前3行为:

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

如何在MySQL中实现它?

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

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

我会这样问:

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

在您的条件下,加入将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

在表中添加所需的输出format@Fahmi添加到帖子中!然后,按时间戳降序对行进行排序是不够的,因为它不提供唯一的结果。如果不按id进行排序,则不会定义结果。很好,然后我的第一个查询工作:时间戳值不是唯一的,因此其中timestamp>selecttimestamp from table WHERE id='current_id'可能是错误的。时间戳值不是唯一的,因此timestamp>=selecttimestamp from table WHERE id=154875可能是错误的wrong@Soheil你是对的,但我想如果你想让它更准确的话,你就不能从中得到更多的准确度按时间戳排序。问题可能是您的id是否已经具有正确的顺序,因此您可以使用该id。我希望它是唯一的,并且按照插入行的顺序。@Soheil-那么问题说明不完整。也许您的步骤1应该说ORDER BY timestamp DESC,id DESC?主要的挑战是遍历复合索引。至少还有两种方法可以表述它。行构造函数方法ts,id@RickJames是的,你说得对。按时间戳顺序DESC,id DESC,两者都是必需的为什么要内部加入?不能通过内部查询实现吗?有两个条件:t.timestamp>c.timestamp和t.timestamp=c.timestamp和t.id>c.id。如果使用子查询,我必须重复子查询select*from tablename,其中id=365847两次,以便引用其列。
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