2017-02-11 9 views
1

フォーラムのリストを返す次の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 
+0

サブクエリ( 'max_p'のエイリアス)のみを実行すると、期待される結果が返されますか? –

+0

うん、実際はそうではありません。/ – Christoffer

+0

次に、そのサブクエリに質問を絞り込む必要があります。 –

答えて

2

私はあなただけJOINに最初のサブクエリでLEFT 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 
+0

それは仕事をしたようです - ありがとう! – Christoffer

関連する問題