如果数据不存在,Mysql查询计数记录

时间:2014-09-22 11:12:20

标签: mysql sql count

我在表格中有以下数据值作为示例。

TId    Date        MID
1     2014-02-01   5
2     2014-03-15   6
3     2014-02-26   5
4     2014-05-03   5
5     2014-04-19   6

现在我试图按月和MID显示记录组,如果数据在MID的特定月份不存在。我尝试使用UNION来显示缺失的月份,但没有得到如下所示的预期结果......

MID     Month    count
 5        1        0
 5        2        2
 5        3        0
 5        4        0
 5        5        1
 6        1        0
 6        2        0
 6        3        1
 6        4        1
 6        5        0     

到目前为止,这是我的询问...希望有人能帮助我们取得好成绩。

SELECT  Months.id `month` ,
COUNT(my_table.date) `count`
FROM 
(
  SELECT 1 ID UNION SELECT 2 ID UNION  SELECT 3 ID UNION SELECT 4 ID 
  UNION  
  SELECT 5 ID UNION SELECT 6 ID
 ) Months
 LEFT JOIN my_table on Months.id=month(my_table.date)                       
 GROUP BY Months.id
 ORDER BY Months.id ASC

1 个答案:

答案 0 :(得分:0)

您似乎想要成对的月份和MID不存在。为此,生成所有组合,然后使用left join匹配它们。不匹配的行是您要返回的行:

SELECT  m.MID, months.month
FROM (SELECT 1 as month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
      SELECT 5 UNION ALL SELECT 6
     ) Months CROSS JOIN
     (SELECT distinct MID from my_table) m LEFT JOIN
     my_table mt
     ON month(mt.date) = months.month and mt.mid = m.mid
WHERE mt.mid is null;

编辑:

我认为问题已经改变了。得到计数:

SELECT m.MID, months.month, count(mt.mid) as cnt
FROM (SELECT 1 as month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
      SELECT 5 UNION ALL SELECT 6
     ) Months CROSS JOIN
     (SELECT distinct MID from my_table) m LEFT JOIN
     my_table mt
     ON month(mt.date) = months.month and mt.mid = m.mid
GROUP m.MID, months.month;