我与MySQL练习,停留在一个场景如下:算作零,如果行不使用GROUP BY与LEFT JOIN存在
我有两个表如下。
Table 1 :
Distinct_dates having DATE as my_date column name:
Table 2:my_records having following fields
record_id,
record_submitter_name,
record_submit_date as DATETIME
I need to get the records submitted by each submitter for each unique month and it should return 0 if no record found for a month.
For example: the below query gives me distinct months from distinct_dates table.
select distinct(DATE_FORMAT(my_date,'%m-%Y')) from distinct_dates;
+--------------------------------+
| (DATE_FORMAT(my_date,'%m-%Y')) |
+--------------------------------+
| 01-2016 |
| 01-2017 |
| 02-2017 |
| 03-2017 |
+--------------------------------+
4 rows in set (0.00 sec)
I am able to get the count of Records in each month by submitter and not getting Zero if No Record found for the particular month?
select distinct(DATE_FORMAT(record_submit_date,'%m-%Y')),count(record_id),record_submitter_name from my_records group by DATE_FORMAT(record_submit_date,'%m-%y'),records_submitter_name;
I have basic understanding of JOINS but not able to get the correct values ,Any help or pointer will be appreciable.
我需要每个record_submitter_name得到记录的计数为每个不同的一个月,如果没有记录在特定月份提交的用户,应该给予零?
进一步使用LEFT加入我能够获得NULL值为不同日期的数据不存在的月份,下面是我查询。
select distinct(DATE_FORMAT(d.my_date,'%m-%Y')),count(m.record_id), m.record_submitter_name from distinct_dates d left join my_records m on DATE_FORMAT(m.record_submit_date,'%m-%Y') = DATE_FORMAT(d.my_date,'%m-%Y') and record_submitter_name='xyz' group by d.my_date;
+----------------------------------+----------------+-------------------+
| (DATE_FORMAT(d.my_date,'%m-%Y')) | count(m.record_id) | record_submitter_name |
+----------------------------------+----------------+-------------------+
| 01-2016 | 1 | xyz |
| 01-2017 | 1 | xyz |
| 02-2017 | 0 | NULL |
| 03-2017 | 0 | NULL |
+----------------------------------+----------------+-------------------+
但使用GROUP BY子句时,它不工作: 使用集团通过近,我还没有收到所要的结果:
select distinct(DATE_FORMAT(d.my_date,'%m-%Y')),count(m.record_id), m.record_submitter_name from distinct_dates d left join my_records m on DATE_FORMAT(m.record_submit_date,'%m-%Y') = DATE_FORMAT(d.my_date,'%m-%Y') group by d.my_date,record_submitter_name;
Following NULL results was not in the output ....
.
+----------------------------------+----------------+-------------------+
| (DATE_FORMAT(d.my_date,'%m-%Y')) | count(m.record_id) | record_submitter_name |
+----------------------------------+----------------+-------------------+
| 01-2016 | 1 | xyz |
| 01-2017 | 1 | xyz |
| 02-2017 | 0 | NULL |
| 03-2017 | 0 | NULL |
+----------------------------------+----------------+-------------------+
是不是有什么毛病GROUP BY子句中使用LEFT JOIN ?
感谢
欢迎来到SO!请参阅[如何提出一个好问题?](https://stackoverflow.com/help/how-to-ask)和[如何创建一个最小,完整和可验证的示例](https:// stackoverflow.com/help/mcve)。请检查您的问题,您在代码中间有正规的文本,很难确切地说出您的问题。 – Olaia