Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query, Count with 0 count

Tags:

sql

count

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?

like image 671
Sergio del Amo Avatar asked Aug 31 '08 10:08

Sergio del Amo


People also ask

Does count in SQL count 0?

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.

How do I count as zero in SQL?

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.

Does count () ignores NULL?

COUNT(expression) does not count NULL values.

What is difference between count (*) and count 1?

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.


1 Answers

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
like image 179
Matt Hamilton Avatar answered Oct 03 '22 09:10

Matt Hamilton