在不对ID进行排序时获取上一行ID

时间:2013-03-21 14:29:17

标签: mysql sql

如何获得之前的&表中具有下述结构的下一个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 |
+----+---------+---------------------+

该表的排序如下:紧急度asc,时间戳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中创建循环结果并找到正确的位置,但这是一个非常快速增加的表。所以这不是一个选择...希望有另一种解决方案,你可以建议

1 个答案:

答案 0 :(得分: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的类似方法来完成。我怀疑你会在这样一个复杂的查询中看到很多性能优势,你肯定会更难维护它......