MySQL查询与COUNT和另一个表的连接列

时间:2013-09-27 15:03:15

标签: mysql join count

我有2个包含多个字段的表。

表1:

+--------+---+---------------+                                                  
| month  | id| VERDICT_id    |                                                  
+--------+------+------------+                                                  
| 201307 | 1 |             1 |                                                  
| 201307 | 2 |             4 |                                                  
| 201307 | 3 |             2 |                                                  
| 201307 | 4 |             2 |                                                  
| 201307 | 5 |          NULL |                                                  
| 201307 | 6 |             1 |                                                  
+--------+------+------------+

对于每个新的'月'都是如此,对于每个唯一的'id','VERDICT_ID'是根据表2中的值设置的。

表2:

+----+----------------------------------+
| id | title                            |
+----+----------------------------------+
|  1 | Passed                           |
|  2 | Failed (Component Fault)         |
|  3 | Failed (User Fault)              |
|  4 | Failed (Hardware Issue)          |
+----+----------------------------------+

我做了一个查询,它给出了以下输出

实际输出:

+--------+------------+----------+
| month  | VERDICT_id | COUNT(*) |
+--------+------------+----------+
| 201307 |          1 |        2 |
| 201307 |          2 |        2 |
| 201307 |          4 |        1 |
+--------+------------+----------+

我想要的是,

+--------+------------+----------+
| month  | VERDICT_id | COUNT(*) |
+--------+------------+----------+
| 201307 |          1 |        2 |
| 201307 |          2 |        2 |
| 201307 |          3 |        0 |
| 201307 |          4 |        1 |
+--------+------------+----------+

这两个输出之间的区别是,如果一个月内不存在任何VERDICT_id,那么我想打印VERDICT_id和COUNT为'0'。

但是通过以下查询,这是不可能的。

select month,VERDICT_id, COUNT(*) FROM Table1 
where (month = 201307) AND (VERDICT_id BETWEEN 1 AND 4) GROUP BY month, VERDICT_id;

Q值。这是否可以使查询将不存在的VERDICT_id和COUNT打印为'0'?

3 个答案:

答案 0 :(得分:2)

试试这个

SELECT v.*, count(t.verdict_id) as cnt FROM 
(
      SELECT month, id as verdict_id 
      from 
          (SELECT DISTINCT month FROM Table1 where (month = 201307)) M , 
          verdictTable
) v
LEFT OUTER JOIN Table1 t ON v.verdict_id = t.verdict_id and v.month = t.month
GROUP BY v.verdict_id, v.month

答案 1 :(得分:0)

select month,VERDICT_id, COUNT(*) as num FROM Table1 
where (month = 201307) AND (VERDICT_id BETWEEN 1 AND 4) 
GROUP BY month, VERDICT_id having num > 0;

答案 2 :(得分:0)

当记录不存在时,您需要强制月份和VERDICT_id字段。 (强制使用DISTINCT LIST。强制VERDICT_id与JOIN无条件地连接到表2)

SELECT LIST.`month` as `month`, Table2.id AS VERDICT_id, COUNT(Detail.id)
FROM 
  (SELECT DISTINCT `month`
  FROM Table1
  WHERE Table1.`month` = 201307) AS LIST
JOIN Table2
LEFT JOIN Table1 AS Detail
  ON LIST.`month` = Detail.`month`
    AND Table2.id = Detail.VERDICT_id
GROUP BY `month`, VERDICT_id
ORDER BY `month`, VERDICT_id;