SQL内连接拼图

时间:2014-11-09 23:30:17

标签: sql

我在论坛中列出主题,使用以下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)。我做错了什么?

1 个答案:

答案 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;