根据评论从论坛中选择帖子

时间:2017-02-11 21:00:48

标签: mysql sql select group-by left-join

我有以下sql将返回论坛列表。在每个论坛下,它将选择带有最新评论的主题。这样可以正常工作,但是当新线程没有任何注释时,不会返回任何内容。

如何解决这个问题?

SELECT  f.Id AS forum_id,
            f.name AS forum_name,
            f.slug AS forum_slug,
            f.image AS forum_image,
            t.Id AS thread_id,
            t.title AS thread_topic,
            t.unixtime AS thread_timestamp,
            p.Id AS post_id,
            p.content AS post_content,
            p.unixtime AS post_timestamp,
            (SELECT COUNT(*) FROM a_comments o WHERE o.forumID=f.Id AND o.teamId = {$teamId}) comments_count,
            (SELECT COUNT(*) FROM a_threads w WHERE w.forumID=f.Id AND w.teamId = {$teamId}) threads_count

    FROM   a_forums f
    LEFT JOIN (SELECT t2.forumID, max(COALESCE(p2.unixtime, t2.unixtime)) as ts, COUNT(p2.unixtime) as post_count
          FROM a_threads t2 
          LEFT JOIN a_comments p2 ON p2.threadId = t2.id
          GROUP BY t2.forumId) max_p ON f.id = max_p.forumId
    LEFT JOIN   a_comments p ON max_p.ts = p.unixtime AND p.teamId = {$teamId} AND p.deleted = 0
    LEFT JOIN   a_threads t ON f.Id = t.forumID AND (max_p.post_count = 0 OR p.threadId = t.ID) AND t.teamId = {$teamId} AND t.deleted = 0
    ORDER BY f.id

1 个答案:

答案 0 :(得分:2)

我认为您只需将第一个子查询中的LEFT JOIN更改为JOIN即可。使用LEFT JOIN,您将获得NULL或评论的无效时间。然后这就抛弃了剩下的逻辑 - 我想。

SELECT f.Id AS forum_id, f.name AS forum_name, f.slug AS forum_slug, f.image AS forum_image,
       t.Id AS thread_id, t.title AS thread_topic, t.unixtime AS thread_timestamp,
       p.Id AS post_id, p.content AS post_content, p.unixtime AS post_timestamp,
       (SELECT COUNT(*) FROM a_comments o WHERE o.forumID=f.Id AND o.teamId = {$teamId}) as comments_count,
       (SELECT COUNT(*) FROM a_threads w WHERE w.forumID=f.Id AND w.teamId = {$teamId}) as threads_count
FROM a_forums f LEFT JOIN 
     (SELECT t2.forumID, max(p2.unixtime) as ts,
             COUNT(p2.unixtime) as post_count
      FROM a_threads t2 JOIN
           a_comments p2
           ON p2.threadId = t2.id
      GROUP BY t2.forumId
     ) max_p
     ON f.id = max_p.forumId LEFT JOIN
     a_comments p
     ON max_p.ts = p.unixtime AND p.teamId = {$teamId} AND
        p.deleted = 0 LEFT JOIN
     a_threads t
     ON f.Id = t.forumID AND (max_p.post_count = 0 OR p.threadId = t.ID) AND t.teamId = {$teamId} AND t.deleted = 0
ORDER BY f.id