2013-09-27 83 views
1

我有兩個包含多個字段的表。MySQL查詢COUNT並從另一個表中加入列

表1:

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

像這樣每一個新的「月」,對於每一個獨特的「身份證」的「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 | 
+--------+------------+----------+ 

的區別該se 2輸出是,如果任何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; 

問:是否可以使查詢打印不存在的VERDICT_id和COUNT爲'0'?

+2

您需要做一個左連接|可能的重複[如何顯示在mySQL組中按零查詢計數行?](http://stackoverflow.com/questions/6602343/how-to-show-rows-with-zero-counts-in-mysql-group - 查詢) – Paulina

回答

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 
+0

我想你的意思是'count(t.id)'。 'count(*)'將包含table1中沒有條目的行。 – 2013-09-27 16:13:47

+0

完美!它正在按照我的要求工作......感謝您的快速幫助......我花了整整一天的時間試圖獲得像這樣的解決方案...... – himansusn

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; 
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; 
+0

該解決方案的工作原理並不一致。對於一些月份,沒有任何行使用VERDICT_id進行更新,並將其設置爲NULL。在這種情況下,此查詢僅將VERDICT_id打印爲「1」,將COUNT(*)打印爲「0」。 – himansusn

相關問題