【问题标题】:MySQL query to order by time and return n rows after specific idMySQL查询按时间排序并在特定ID后返回n行
【发布时间】:2020-08-05 10:21:42
【问题描述】:

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

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

我需要什么:

  1. 按时间戳降序对行进行排序
  2. 然后在 id=something 之后(如下)返回 24 行

例如对于 id=962548,预期输出的前 3 行将是:

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

如何在 MySQL 中实现?

【问题讨论】:

  • 以表格格式添加所需的输出
  • @Fahmi 已添加到帖子中!
  • 然后按时间戳降序对行进行排序是不够的,因为它没有提供唯一的结果。
  • 如果不按id排序also,则结果未定义。
  • 好的,那么我的第一个查询有效:db-fiddle.com/f/v5HnGZoB929ZnQ2RiG6iV7/2

标签: mysql sql database mariadb


【解决方案1】:

加入查询,根据您的条件将 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

【讨论】:

  • 你为什么要内联?不能通过内部查询来实现吗?
  • 有两个条件:t.timestamp > c.timestamp and (t.timestamp = c.timestamp and t.id > c.id)。如果我使用子查询,我将不得不重复子查询select * from tablename where id = 365847 两次,这样我才能引用它的列。
【解决方案2】:

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

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

【讨论】:

  • 时间戳值不是唯一的,所以 WHERE timestamp&gt;(select timestamp from table where id = 'current_id') 可能是错误的
【解决方案3】:

我会这样查询:

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

【讨论】:

  • 时间戳值不是唯一的,所以 timestamp &gt;= (SELECT timestamp FROM tab WHERE id = 154875) 可能是错误的
  • @Soheil 你是对的,但我想如果你希望它按时间戳排序,你就无法从中获得更高的准确性。一个问题可能是你的 id 是否已经有正确的顺序,所以你可以使用 id。我希望它是唯一的并且按照行的插入顺序。
  • @Soheil - 那么问题说明不完整。也许你的第一步应该说ORDER BY timestamp DESC, id DESC
  • 主要挑战是遍历复合索引。至少还有另外两种方法来制定它。 “行构造函数”方法(ts,id)&lt;(i.ts,123) 可能是最好的,但适用于较新版本的 MySQL/MariaDB。
  • @RickJames 是的,你是对的。 ORDER BY timestamp DESC, id DESC,两者都是必需的
猜你喜欢
  • 2012-01-09
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多