I have 3 tables:
id, name, description
thread_id, forum_id, user_id, title, content, views
post_id, thread_id, author_id, content, date
What I want to do is to get all the threads in a forum, and get the post count of every thread. So I get every thread (WHERE forum_id = whatever) and then I LEFT JOIN with the table posts so in order to count the results. But something is not working. Here is my query:
SELECT t.*, u.nick, COUNT(p.post_id) AS postcount
FROM
threads t
LEFT JOIN
users u
ON
u.id = t.user_id
LEFT JOIN
posts p
ON
p.thread_id = t.thread_id
WHERE
t.forum_id = $this->forumID
This query will only show (I think) the threads that have any post on it. I also tried using the GROUP BY statement but it makes MySQL error...
How can I solve this?
----------- EDIT: I tried adding GROUP BY t.thread_id, however, as I said before, MySQL errors:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE t.forum_id = 2' at line 15
Full query:
SELECT t.*, u.nick, COUNT(p.post_id) AS postcount
FROM
threads t
LEFT JOIN
users u
ON
u.id = t.user_id
LEFT JOIN
posts p
ON
p.thread_id = t.thread_id
GROUP BY
t.thread_id
WHERE
t.forum_id = $this->forumID
EDIT 2:
My bad, I put the GROUP BY statement where it wasn't meant to be. It is now solved.
To achieve this for multiple tables, use the UNION ALL. select sum(variableName. aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName; Let us implement the above syntax.
Left Outer Join returns all of the rows in the current data and all the data from the matching rows in the joined data, adding rows when there is more than one match. This can result in an expanded row count.
MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.
Introduction to MySQL LEFT JOIN clauseThe LEFT JOIN allows you to query data from two or more tables. Similar to the INNER JOIN clause, the LEFT JOIN is an optional clause of the SELECT statement, which appears immediately after the FROM clause.
GROUP BY was the right way to go, so just add: GROUP BY t.thread_id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With