MYSQL - 加入3个表按月分组,包括空月

时间:2016-12-13 22:10:16

标签: mysql sql select join group-by

我有3个表:T_AUDITS,T_MONTHS和T_REGIONS。

我试图获得多少次审核'按月和区域分组,包括零当不存在时对该月进行审核。

我的查询仅获得具有审核功能的月份。我无法通过0次审核获得月份。

SELECT 
 MON.MON_DESC,
 REG.REG_ID,
 COUNT(AUD.AUD_ID) 
FROM
 T_MONTHS MON 
 LEFT JOIN T_AUDITS AUD 
   ON (
     MON.MON_ID = MONTH(AUD.AUD_START_DATE)
   ) 
   RIGHT JOIN T_REGIONS REG 
   ON (
     REG.REG_ID = AUD.AUD_REGION
   )  
GROUP BY    MON.MON_ID, REG.REG_ID
ORDER BY REG.REG_ID,
 MON.MON_ID

我明白了:

MON_NAME  |REG_ID        |COUNT(AUD.AUD_ID) |
----------|--------------|------------------|
January   |AMERICA       |52                |
February  |AMERICA       |51                |
March     |AMERICA       |57                |
April     |AMERICA       |66                |
May       |AMERICA       |54                |
January   |ASIA          |58                |
February  |ASIA          |29                |
April     |ASIA          |71                |
May       |EUROPE        |59                |

我试图获得:

MON_NAME  |REG_ID        |COUNT(AUD.AUD_ID) |
----------|--------------|------------------|
January   |AMERICA       |52                |
February  |AMERICA       |51                |
March     |AMERICA       |57                |
April     |AMERICA       |66                |
May       |AMERICA       |54                |
January   |ASIA          |58                |
February  |ASIA          |29                |
March     |ASIA          |0                 |
April     |ASIA          |59                |
May       |ASIA          |0                 |
January   |EUROPE        |0                 |
February  |EUROPE        |0                 |
March     |EUROPE        |0                 |
April     |EUROPE        |0                 |
May       |EUROPE        |79                |

任何想法?在此先感谢!!!

1 个答案:

答案 0 :(得分:3)

尝试使用CROSS JOIN获取所有月份和地区组合,然后使用LEFT JOIN进行审核。

SELECT 
 MON.MON_DESC,
 REG.REG_ID,
 IFNULL(COUNT(AUD.AUD_ID), 0) AS count
FROM T_MONTHS MON 
CROSS JOIN T_REGIONS REG
LEFT JOIN T_AUDIT AUD ON MONTH(AUD.AUD_START_DATE) = MON.MON_ID AND REG.REG_ID = AUD.AUD_REGION
GROUP BY REG.REG_ID, MON.MON_ID
ORDER BY REG.REG_ID, MON.MON_ID