MySQL组以null值连接

时间:2014-04-03 22:59:07

标签: mysql sql join

我正在尝试创建一个MySQL查询,该查询将返回与在日期范围内创建的用户相关的客户数量。我有以下查询:

SELECT COUNT(`customer`.`user_id`) as `count`, `user`.`first_name`,  `user`.`last_name`
FROM (`user`) 
LEFT JOIN `customer` ON `user`.`id` = `customer`.`user_id`
WHERE `customer`.`date_created` >= '2014-03-27 23:41:28' AND `customer`.`date_created` <= '2014-04-04 00:41:28'
GROUP BY `customer`.`user_id` 
ORDER BY `count`
LIMIT 5

如果我删除了where子句,那么我会得到我期望的结果,包括空值:

count   first_name   last_name
0       Name         Name
1       Name         Name
3       Name         Name
10      Name         Name

问题在于,当我引入where子句时,我没有得到返回的没有count值的行。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

将where where条件移动到ON()子句,这样它将过滤右表中的结果而不是所有结果集,并将为左表中的不匹配结果生成0计数

SELECT COUNT(`customer`.`user_id`) as `count`, 
`user`.`first_name`, 
 `user`.`last_name`
FROM `user` 
LEFT JOIN `customer` ON (
`user`.`id` = `customer`.`user_id`
AND `customer`.`date_created` >= '2014-03-27 23:41:28'
 AND `customer`.`date_created` <= '2014-04-04 00:41:28')
GROUP BY `user`.`id` 
ORDER BY `count`
LIMIT 5