Select 连接语句中的上一条和下一条记录

Select previous and next records in join statement

在查看帖子的页面上,我认为最好有下一篇和上一篇帖子的链接。我认为我应该在 1 个查询中获得这 3 条记录,因为我很聪明而且我有很多时间可以浪费。所以你可能猜到了我做不到,但我有兴趣找到解决方案。这是我的

SELECT a.id,
       a.title,
       a.body,
       p.id    AS prev_id,
       p.title AS prev_title,
       n.id    AS next_id,
       n.title AS next_title
FROM   posts a
       LEFT JOIN posts p
              ON p.id < a.id
       LEFT JOIN posts n
              ON n.id > a.id
WHERE  a.id = ?
LIMIT  1

问题是,对于 prev_idprev_title,我总是在 table 中得到 第一个 记录。我尝试添加 ORDER BY 但它似乎并没有真正影响连接。我怎样才能像示例中那样使用连接 select 前一条而不是第一条记录?

希望本文对您有所帮助:

SELECT a.id,
       a.title,
       a.body,
       p.id    AS prev_id,
       p.title AS prev_title,
       n.id    AS next_id,
       n.title AS next_title
FROM   posts a
       INNER JOIN
       (
            SELECT 
                _a.id AS RefID,
                MIN(_a.id - _p.id) AS MinDistPrev,
                MIN(_n.id - _a.id) AS MinDistNext
            FROM   
                posts _a
                LEFT JOIN posts _p
                      ON _p.id < _a.id
                LEFT JOIN posts _n
                      ON _n.id > _a.id
            WHERE  
                _a.id = ?
            GROUP BY
                _a.id
       ) AS _PrevNextDist
        ON _PrevNextDist.RefID = a.ID
       LEFT JOIN posts p
              ON p.id < a.id
                 AND a.id - p.id = _PrevNextDist.MinDistPrev
       LEFT JOIN posts n
              ON n.id > a.id
                 AND n.id - a.id = _PrevNextDist.MinDistNext
LIMIT  1

另外,在原代码中加入ORDER BY p.id DESC也解决了问题

SELECT a.id,
       a.title,
       a.body,
       p.id    AS prev_id,
       p.title AS prev_title,
       n.id    AS next_id,
       n.title AS next_title
FROM   posts a
       LEFT JOIN posts p
              ON p.id < a.id
       LEFT JOIN posts n
              ON n.id > a.id
WHERE  a.id = ?
ORDER BY p.id DESC
LIMIT  1