[英]What is the correct MySQL syntax for a query with a COUNT from another table as a column?
[英]MySQL query with COUNT and join column from another table
我有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”,都會根據表2中的值設置“ VERDICT_ID”。
表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;
問:是否可以進行查詢以將不存在的VERDICT_id和COUNT打印為“ 0”?
嘗試這個
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
嘗試
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;
當記錄不存在時,您需要強制使用month和VERDICT_id字段。 (使用DISTINCT LIST強制使用月份。使用JOIN強制使用VERDICT_id,而沒有對Table2的條件)
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.