让自己陷入困境......
我们在嵌套集模型中使用左右限制来存储论坛帖子,我需要选择最新回复订购的帖子。
相关表格结构:
id lft rght date
1 1 4 2011-01-01
2 5 8 2011-01-02
3 6 7 2011-01-04
4 2 3 2011-01-05
所以我需要得到
id last_reply latest
1 4 2011-01-05
2 6 2011-01-04
非常感谢任何帮助。
答案 0 :(得分:1)
SELECT pt.*, MAX(pc.date) AS latest
FROM post pt
JOIN post pc
ON pc.lft BETWEEN pt.lft AND pt.rgt
WHERE NOT EXISTS
(
SELECT NULL
FROM post pu
WHERE pt.lft BETWEEN pu.lft AND pu.rgt
)
GROUP BY
pt.id
ORDER BY
latest DESC
嵌套集不适合选择深度级别,因此效率不高。
我建议将线程开始id
与每个帖子一起存储,并在(starter, date)
上创建一个综合索引。
这样,你可以使用:
SELECT pt.*,
MAX(date) AS latest
FROM post pu
JOIN post pt
ON pt.id = pu.starter
GROUP BY
pu.starter
ORDER BY
latest DESC
会更快。