I have three tables: page, attachment, page-attachment
I have data like this:
page
ID NAME
1 first page
2 second page
3 third page
4 fourth page
attachment
ID NAME
1 foo.word
2 test.xsl
3 mm.ppt
page-attachment
ID PAGE-ID ATTACHMENT-ID
1 2 1
2 2 2
3 3 3
I would like to get the number of attachments per page also when that number is 0. I have tried with:
select page.name, count(page-attachment.id) as attachmentsnumber
from page
inner join page-attachment on page.id=page-id
group by page.id
I am getting this output:
NAME ATTACHMENTSNUMBER
second page 2
third page 1
I would like to get this output:
NAME ATTACHMENTSNUMBER
first page 0
second page 2
third page 1
fourth page 0
How do I get the 0 part?
The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.
It's all about the JOIN type. Using the suitable JOIN is crucial when you want to include zeros in the COUNT() aggregate. If you now use the aggregate function COUNT() , like in the code above, it will not count the NULL values and the result will be zero.
COUNT(expression) does not count NULL values.
The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values. The semantics for COUNT(1) differ slightly; we'll discuss them later. However, the results for COUNT(*) and COUNT(1) are identical.
Change your "inner join" to a "left outer join", which means "get me all the rows on the left of the join, even if there isn't a matching row on the right."
select page.name, count(page-attachment.id) as attachmentsnumber
from page
left outer join page-attachment on page.id=page-id
group by page.name
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