我在论坛中列出主题,使用以下SQL;
select t.* , lp.latestpost, lp.lpname
from forum_topics as t
inner join (
select p.topic, max(p.date) as latestpost, p.author_name as lpname
from forum_replies p
group by p.topic
) lp on lp.topic = t.id
order by lp.latestpost desc
LIMIT 20
问题是它永远不会给我正确的主题名称(lpname)。我做错了什么?
答案 0 :(得分:1)
您正在获取姓氏的任意值,因为您使用的是MySQL扩展。作为一般规则,聚合的select
部分中的列应位于聚合函数或group by
子句中。在您的情况下,p.author_name
既不是。
您可以使用涉及group_concat()
和substring_index()
select t.* , lp.latestpost, lp.lpname
from forum_topics as t inner join
(select p.topic, max(p.date) as latestpost,
substring_index(group_concat(p.author_name order by p.date desc separator '|'
), '|', 1) as as lpname
from forum_replies p
group by p.topic
) lp
on lp.topic = t.id
order by lp.latestpost desc
LIMIT 20;