这是 SQL 查询:
select user.*, count(call_out_end.id) as calls
from user
left join call_out_end on call_out_end.employer_id = user.id
where user.id = 949 and call_out_end.callstart >= '2018-12-09 00:00:00'
group by user.id
并且此查询正好返回 0 行(应返回 1 行,列调用 = 0)。
如果我确实将 SQL 查询更改为:
select user.*, count(call_out_end.id) as calls
from user
left join call_out_end on call_out_end.employer_id = user.id
where user.id = 949
group by user.id
MySQLWorkbench 返回 1 行:
...但这不是我想要的:)
我想提一下,没有满足条件的记录:call_out_end.callstart >= '....'
,所以我希望收到 0 个电话。
我哪里做错了?
在left join
需要进入on
子句的第二个表上进行过滤:
select u.*, count(coe.id) as calls
from user u left join
call_out_end coe
on coe.employer_id = user.id and
coe.callstart >= '2018-12-09'
where u.id = 949
group by u.id;
当条件在WHERE
子句中时,外连接变成内连接。为什么?不匹配的值callstart
有一个NULL
值并且比较失败。
请注意,我还向查询添加了表别名。这使得编写和阅读更容易。我还从日期常量中删除了时间部分。这是不必要的。
的group by u.id
是好的,假设u.id
是在一个主键users
(它无疑是)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句