Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

sql - How to get a count even if there are no results corresponding mysql?

I am formalating a query to give the number of reports submitted over the last year ordered by date. I get the current year and month with php:

$year = date('Y') - 1;
$month = date('m');

and execute the following query: SQL:

SELECT month(date_lm) AS `month` ,
count(*) AS `count`
FROM `reports` 
WHERE (status = 'submitted') 
AND (date_lm > 2012-08) 
GROUP BY month(date_lm) 
ORDER BY month(date_lm) ASC

And because there has only been 1 submitted in the last year it gives me only 1 result...

| month  |  count  |
|   7    |    1    |

But I would like the result set to show:

| month  |  count  |
|   9    |    0    |
|   10   |    0    |
|   11   |    0    |
|   12   |    0    |
|   1    |    0    |
|   2    |    0    |
|   3    |    0    |
|   4    |    0    |
|   5    |    0    |
|   6    |    0    |
|   7    |    1    |
|   8    |    0    |

Is that possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to do this, you could create a 'month' table and then use a left outer join between that table and the reports table.

I've never used mysql so apologies if the syntax is slightly off, but this would be the query:

SELECT months.monthNumber,
    count(reports.id) AS `count`
FROM `months` left outer join `reports` on months.monthNumber = month(reports.date_lm) 
WHERE (status = 'submitted') 
AND (date_lm > 2012-08) 
GROUP BY monthNumber
ORDER BY monthNumber ASC

Importantly, the count should be of a column in the reports table, not the months table, or else you would never get a zero.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...