我使用此查询来获取 mysql 事件表中的下一个和上一个事件的 ID:
SELECT e.id AS current, prev.id AS previous, next.id AS next
FROM events e
CROSS JOIN
(
SELECT id FROM events
WHERE date < '{$result['date']}'
ORDER BY date DESC
LIMIT 1
) prev
CROSS JOIN
(
SELECT id
FROM events
WHERE date > '{$result['date']}'
ORDER BY date
LIMIT 1
) next
WHERE e.date = '{$result['date']}'
此查询工作正常。
让我们假装桌子看起来像这样:
ID | EVENT_NAME | DATE
------------------------------
1 | test event 1 | 2012-01-01
2 | test event 2 | 2012-01-02
3 | test event 3 | 2012-02-03
如果我使用$result['date']
as运行查询2012-01-02
,则会返回:
Array
(
[0] => Array
(
[current] => 2
[previous] => 1
[next] => 3
)
)
但是,如果我使用$result['date']
as 2012-01-01
OR运行查询2012-01-03
,则会返回一个空的结果集!
如果上一个或下一个日期不存在,因为传递的日期是最高或最低的,我仍然需要结果集来返回下一个或上一个
例如
$result['date']
因此,如果我使用as运行查询2012-01-01
,我需要结果集:
Array
(
[0] => Array
(
[current] => 1
[next] => 2
)
)
OR
Array
(
[0] => Array
(
[current] => 1
[previous] => NULL
[next] => 2
)
)