This is my first time here on Stack. I'm attempting to build a message board (forum) using PHP
and MySQL
. I'd like to display a table in PHP
with the following information:
- one column displaying all current forums
- another column displaying the total number of threads and posts per forum.
- last column for displaying the latest thread created.
This is the query I have that returns the correct latest thread, but not the correct count:
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
These are the results of the post and thread counts, it's only counting the threads and posts in the latest thread of each forum:
post count thread count
- -
7 1
1 1
1 1
1 1
0 0
This query gets the correct post and threads counts for each forum:
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;
The results for the post and thread count for each forum should be:
post count thread count
- -
7 1
1 1
3 2
1 1
0 0
Is there anyway I can combine the two queries, or fix the first one, so I get the correct output?
Please use the following tables in your suggestions:
users, threads, forums, posts
I'm new to PHP
and MySQL
, so I'm sorry if it's not the right way to go about doing something like this.
Your help is very much appreciated!