3

我使用此查询来获取 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-01OR运行查询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
    )
)
4

2 回答 2

3

您可以使用 1=1 的 LEFT JOIN

SELECT e.id AS current, prev.id AS previous, next.id AS next 
FROM events e 
LEFT JOIN  
( 
    SELECT id FROM events  
    WHERE date < '{$result['date']}'  
    ORDER BY date DESC  
    LIMIT 1 
) ON prev 1=1 
LEFT JOIN  
( 
    SELECT id 
    FROM events  
    WHERE date > '{$result['date']}'  
    ORDER BY date  
    LIMIT 1 
) ON next 1=1 
WHERE e.date = '{$result['date']}' 
于 2012-07-13T11:41:01.087 回答
1

您可能会使用子查询:

SELECT e.id AS current, 
(
    SELECT id 
    FROM events 
    WHERE date < '{$result['date']}' 
    ORDER BY date DESC 
    LIMIT 1
) AS previous,
(
    SELECT id
    FROM events 
    WHERE date > '{$result['date']}' 
    ORDER BY date 
    LIMIT 1
) AS next
FROM events e
WHERE e.date = '{$result['date']}'
于 2012-07-13T11:50:40.463 回答