选择与右表中的记录数不匹配的记录数

时间:2017-11-02 11:49:29

标签: sql group-by count

假设我们有以下 error_description 表:

+----------+-------------+
| error_id | error_token |
+----------+-------------+
| 1        | error_1     |
+----------+-------------+
| 2        | error_2     |
+----------+-------------+
| 3        | error_3     |
+----------+-------------+
| 4        | error_4     |
+----------+-------------+
| 5        | error_5     |
+----------+-------------+
| 6        | error_6     |
+----------+-------------+

orders_error 表:

+----------+----------+
| order_id | error_id |
+----------+----------+
| 1        | 1        |
+----------+----------+
| 2        | 1        |
+----------+----------+
| 3        | 2        |
+----------+----------+
| 4        | 3        |
+----------+----------+
| 5        | 1        |
+----------+----------+
| 6        | 1        |
+----------+----------+
| 7        | 2        |
+----------+----------+
| 8        | 2        |
+----------+----------+
| 9        | 3        |
+----------+----------+
| 10       | 4        |
+----------+----------+

要求获取每个错误的总发生次数,包括那些从未发生的错误。 结果应该是这样的:

+-------------+-------------+
| error_token | total_count |
+-------------+-------------+
| error_1     | 4           |
+-------------+-------------+
| error_2     | 3           |
+-------------+-------------+
| error_3     | 2           |
+-------------+-------------+
| error_4     | 1           |
+-------------+-------------+
| error_5     | 0           |
+-------------+-------------+
| error_6     | 0           |
+-------------+-------------+

我使用的查询如下:

SELECT err.token,
       COUNT( ord.order_id )
  FROM       error_description err
  LEFT JOIN  order_error ord ON ( err.error_id = ord.error_id )
 GROUP BY err.token          
;

但我只得到了发生的错误(error_1直到error_4)。

我需要包含那些从未发生过的错误吗?

1 个答案:

答案 0 :(得分:1)

根据您的表定义更新了列名称。

SELECT err.error_token,
       COUNT( ord.order_id ) AS total_count 
FROM  error_description err
LEFT JOIN  order_error ord ON err.error_id = ord.error_id
GROUP BY err.error_token