1

如何从具有如下结构的表中获取上一个和下一个 id:

+----+---------+---------------------+
| id | urgency | timestamp           |
+----+---------+---------------------+
|  1 | 0       | 2013-01-01 00:00:00 |
|  2 | 2       | 2013-01-01 00:00:00 |
|  3 | 1       | 2013-01-05 09:30:00 |
|  4 | 2       | 2013-01-01 00:00:00 |
|  5 | 2       | 2013-01-01 00:00:00 |
|  6 | 1       | 2013-01-06 10:00:00 |
|  7 | 0       | 2013-01-01 00:00:00 |
|  8 | 0       | 2013-01-03 00:00:00 |
|  9 | 1       | 2013-02-01 13:30:00 |
| 10 | 0       | 2013-01-04 00:00:00 |
+----+---------+---------------------+

表格排序如下:urgency asc、timestamp asc、id asc

这是排序表:

+----+---------+---------------------+
| id | urgency | timestamp           |
+----+---------+---------------------+
|  1 | 0       | 2013-01-01 00:00:00 |
|  7 | 0       | 2013-01-01 00:00:00 |
|  8 | 0       | 2013-01-03 00:00:00 |
| 10 | 0       | 2013-01-04 00:00:00 |
|  3 | 1       | 2013-01-05 09:30:00 |
|  6 | 1       | 2013-01-06 10:00:00 |
|  9 | 1       | 2013-02-01 13:30:00 | <= CURRENT_ID
|  2 | 2       | 2013-01-01 00:00:00 |
|  4 | 2       | 2013-01-01 00:00:00 |
|  5 | 2       | 2013-01-01 00:00:00 |
+----+---------+---------------------+

有没有办法从 MySQL 中选择位置为 CURRENT_ID - 1 或 CURRENT_ID + 1 的东西?

我能做的是执行一个简单的查询:

SELECT
    id
FROM
    MY_TABLE
ORDER BY
    urgency asc,
    timestamp asc,
    id asc

在 PHP 中创建一个循环结果并找到正确的位置,但这是一个会很快增加的表格。所以这不是一个选择......希望您可以提供另一种解决方案

4

1 回答 1

3

对于以前的:

SELECT prev.id
FROM my_table current
JOIN my_table prev
  ON (prev.urgency < current.urgency) 
     OR (prev.urgency = current.urgency 
        AND (prev.timestamp < current.timestamp 
            OR (prev.timestamp = current.timestamp AND prev.id < current.id)))
WHERE current.id = @currentId
ORDER BY prev.urgency desc, prev.timestamp desc, prev.id desc
LIMIT 1

接下来:

SELECT next.id
FROM my_table current
JOIN my_table next
  ON (next.urgency > current.urgency) 
     OR (next.urgency = current.urgency 
        AND (next.timestamp > current.timestamp 
            OR (next.timestamp = current.timestamp AND next.id > current.id)))
WHERE current.id = @currentId
ORDER BY next.urgency asc, next.timestamp asc, next.id asc
LIMIT 1

这里是 Sqlfiddle

尝试在单个查询中同时获取它们更具挑战性,但可以通过使用嵌套分组代替 LIMIT 的类似方法来完成。我怀疑您会在如此复杂的查询中看到很多性能优势,而且您肯定会更难维护它......

于 2013-03-21T14:32:29.760 回答