我有以下 MySQL 表结构:
mysql> desc customers;
+---------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+-------------+------+-----+---------+-------+
| hash | varchar(32) | NO | PRI | NULL | |
| date_joined | date | NO | | NULL | |
| agent_code | int(5) | NO | UNI | | |
+---------------------+-------------+------+-----+---------+-------+
mysql> desc persons;
+--------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+-------------+------+-----+---------+-------+
| agent_code | int(5) | NO | UNI | | |
| team_id | int(2) | YES | | 0 | |
| hash | varchar(32) | NO | PRI | NULL | |
+--------------------+-------------+------+-----+---------+-------+
mysql> desc teams;
+--------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| leader | varchar(32) | NO | UNI | NULL | |
+--------+-------------+------+-----+---------+----------------+
我希望按团队生成销售报告。
我正在使用的 SQL 查询如下:
SELECT COUNT(`customers`.`agent_code) AS `customer_count`, `teams`.`name`
FROM `customers`
JOIN `persons` ON `customers`.`agent_code` = `persons`.`agent_code`
JOIN `teams` ON `persons`.`team_id` = `teams`.`id`
GROUP BY `teams`.`name`
它显示以下信息:
+----------------+--------+
| customer_count | name |
+----------------+--------+
| 3 | Team 1 |
+----------------+--------+
但是,我想查看数据库中所有团队的“customer_count”,即使给定团队的 customer_count 为空(或零)。我的数据库中有 15 个团队,所以我希望看到类似的内容:
+----------------+--------+
| customer_count | name |
+----------------+--------+
| 3 | Team 1 |
| 0 | Team 2 |
| 0 | Team 3 |
| 0 | Team 4 |
+----------------+--------+
我试图执行以下查询的一些变体,但我总是收到一个错误,说 OUTER JOIN 的语法不正确,即使我已经阅读了文档,并且它是正确的。
SELECT COUNT( `customers`.`agent_code` ) AS `customer_count` , `teams`.`name`
FROM `customers`
LEFT JOIN `persons` ON `customers`.`agent_code` = `persons`.`agent_code`
LEFT OUTER JOIN `teams` ON `persons`.`team_id` = `teams`.`id`
GROUP BY `teams`.`name`
如何更改当前查询以显示此类结果?