Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get count of another table in a left join

I have multiple tables

post
    id  Name
    1   post-name1
    2   post-name2

user
    id  username
    1   user1
    2   user2

post_user
    post_id   user_id
    1         1
    2         1

post_comments
    post_id   comment_id
    1         1
    1         2
    1         3

I am using a query like this:

SELECT post.id, post.title, user.id AS uid, username
FROM `post`
LEFT JOIN post_user ON post.id = post_user.post_id
LEFT JOIN user ON user.id = post_user.user_id
ORDER BY post_date DESC

It works as intended. However I would like the get the number of comments for each post too. So how can I modify the this query so I can get the count of comments.

Any ideas?

like image 929
Sinan Avatar asked Jun 02 '10 16:06

Sinan


People also ask

How do I count from another table in SQL?

SELECT COUNT(*) FROM table_name; The COUNT(*) function will return the total number of items in that group including NULL values. The FROM clause in SQL specifies which table we want to list.

How do I count in two tables?

Select COUNT(*) from multiple tables The following query COUNT the number of rows from two different tables (here we use employees and departments) using COUNT(*) command.

How do you count rows in SQL using join?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How can LEFT join increase row count?

Left joins can increase the number of rows in the left table if there are multiple matches in the right table.


1 Answers

SELECT post.id, post.title, user.id AS uid, username, COALESCE(x.cnt,0) AS comment_count
FROM `post`
LEFT JOIN post_user ON post.id = post_user.post_id
LEFT JOIN user ON user.id = post_user.user_id
LEFT OUTER JOIN (SELECT post_id, count(*) cnt FROM post_comments GROUP BY post_id) x ON post.id = x.post_id
ORDER BY post_date DESC

EDIT: made it an outer join in case there aren't any comments

EDIT2: Changed IsNull to Coalesce

like image 140
dcp Avatar answered Sep 30 '22 00:09

dcp