Question

so I have the following tables:

Article

  • article_id

Comment

  • comment_id
  • article_id

What I want to do is search for all articles despite having or not comments and show the article id and how many comments it has.

Imagine that I have two articles and just the first one has comments. I can't get to make a query that shows me both of them and their comments number.

EDIT 1:

I made the following query after reading the responses and I'm almost there! There is only a problem. Instead of getting 0 when a article has no comments, I get 1.

SELECT *,COUNT(a.article_id) FROM article as a LEFT JOIN comment as c ON a.article_id = c.article_id GROUP BY a.article_id;

EDIT 2:

A simple mistake. I changed "COUNT(a.article_id)" to "COUNT(C.article_id)". So obvious! :) Thanks for the help people ;)

SELECT *,COUNT(c.article_id) FROM article as a LEFT JOIN comment as c ON a.article_id = c.article_id GROUP BY a.article_id;

Was it helpful?

Solution

Try this:

SELECT * FROM Article as a INNER JOIN Comment as c ON a.article_id = c.article_id;

OTHER TIPS

You want to

SELECT 
    IFNULL(COUNT(c.comment_id),0) AS 'Comment Count' , 
    a.article_id 
FROM 
  article a 
LEFT JOIN 
  comment c 
  ON c.article_id

What I'm doing here is using MySQL's LEFT JOIN to compare the comment table against the article table (our reference). Where there's a match between the c.article_id and a.article_id, we grab the data.

Try LEFT JOIN

Select 
article_id, 
count(comment_id)
from 
article a
LEFT JOIN comment c on (a.article_id=c.article_id)
GROUP BY article_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top