获得正确的 MAX 结果,但在留言板的 MySQL 中没有正确的 COUNT 值

Getting correct MAX result, but not the correct COUNT values in MySQL for message board

这是我第一次来到 Stack。我正在尝试使用 PHPMySQL 构建留言板(论坛)。我想在 PHP 中显示 table,其中包含以下信息:

  1. 一栏显示所有当前论坛
  2. 另一列显示线程总数和每个 posts 论坛。
  3. 显示最新创建的线程的最后一列。

这是我的查询 returns 正确的最新线程,但不是正确的计数:

SELECT 
       forums.*,
       threads.thread_id,
       threads.thread_topic,
       threads.user_id,
       users.user_name, 
       threads.thread_date, 
       COUNT(DISTINCT threads.thread_id) AS thread_count,
       COUNT(DISTINCT posts.post_id) AS post_count
   FROM forums 
   LEFT OUTER JOIN threads
      ON forums.forum_id = threads.forum_id
      AND threads.thread_date = 
         (SELECT MAX(threads.thread_date) AS last_topic
             FROM threads 
             WHERE forums.forum_id = threads.forum_id)
   LEFT JOIN users 
      ON users.user_id = threads.user_id
   LEFT JOIN posts 
      ON threads.thread_id = posts.thread_id
   GROUP BY forums.forum_id

这些是 post 和线程计数的结果,它只计算每个论坛最新线程中的线程和 posts:

post count  thread count
    -             -
    7             1
    1             1
    1             1
    1             1
    0             0

此查询获得正确的 post 和每个论坛的线程计数:

SELECT 
       COUNT(DISTINCT posts.post_id) AS post_count, 
       COUNT(DISTINCT threads.thread_id) AS thread_count
   FROM forums 
   LEFT OUTER JOIN threads 
      ON threads.forum_id = forums.forum_id
   LEFT JOIN posts 
      ON threads.thread_id = posts.thread_id
   GROUP BY forums.forum_id;

post 的结果和每个论坛的线程数应该是:

post count  thread count
        -             -
        7             1
        1             1
        3             2
        1             1
        0             0

我是否可以合并这两个查询,或者修复第一个查询,以便获得正确的输出?

请在您的建议中使用以下 table:

users, threads, forums, posts

我是 PHPMySQL 的新手,如果这样做不正确,我深表歉意。

非常感谢您的帮助!

SELECT
    forums.*,
    counts.thread_count,
    counts.post_count,
    threads.*,           -- last thread
    users.*              -- user of last thread
FROM forums
LEFT JOIN (
    SELECT 
        forums.forum_id,
        COUNT(DISTINCT threads.thread_id) AS thread_count,
        COUNT(DISTINCT posts.post_id) AS post_count
    FROM forums 
    LEFT JOIN threads ON threads.forum_id = forums.forum_id
    LEFT JOIN posts ON posts.thread_id = threads.thread_id
    GROUP BY forums.forum_id
) counts ON counts.forum_id = forums.forum_id
LEFT JOIN (
    SELECT
        forums.forum_id,
        threads.thread_id,
    FROM forums
    JOIN threads ON forums.forum_id = threads.forum_id
    AND threads.thread_date = 
        (SELECT MAX(threads.thread_date) AS last_topic
            FROM threads 
            WHERE forums.forum_id = threads.forum_id)
) last_thread ON last_thread.forum_id = forums.forum_id
LEFT JOIN threads ON threads.thread_id = last_thread.thread_id
LEFT JOIN users ON users.user_id = threads.user_id