在查看帖子的页面上,我认为为下一篇和之前的帖子提供链接是个不错的主意。我认为我应该在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_id
和prev_title
我总是在表格中获得第一个记录。我尝试添加ORDER BY
,但它似乎并没有真正影响加入。如何使用示例中的连接选择上一个而不是第一个记录?
答案 0 :(得分:1)
我希望你能发现这个有用的东西:
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