php – 在MySQL中,如何选择空记录
作者:互联网
我有以下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为null(或为零).我的数据库中有15个团队,所以我希望看到类似的东西:
+----------------+--------+
| customer_count | name |
+----------------+--------+
| 3 | Team 1 |
| 0 | Team 2 |
| 0 | Team 3 |
| 0 | Team 4 |
+----------------+--------+
我试图执行以下Query的一些变体,但我总是得到一个错误,说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`
如何更改当前查询以显示此类结果?
解决方法:
你有错误得到主表是人 – 我建议你的主表是团队
SELECT COUNT(`customers`.`id`) AS `customer_count` , `teams`.`name`
FROM `teams`
JOIN `persons` ON `persons`.`team_id` = `teams`.`id`
LEFT JOIN `customers` ON `customers`.`agent_code` = `persons`.`agent_code`
GROUP BY `teams`.`name`
更新:如果您有空团队,则需要在人员上设置左连接
SELECT COUNT(`customers`.`id`) AS `customer_count` , `teams`.`name`
FROM `teams`
LEFT JOIN `persons` ON `persons`.`team_id` = `teams`.`id`
LEFT JOIN `customers` ON `customers`.`agent_code` = `persons`.`agent_code`
GROUP BY `teams`.`name`
标签:php,mysql,select,outer-join 来源: https://codeday.me/bug/20190704/1375742.html