select d.name as 'name', sum(r.distance) as 'sum_distance'
from driver d
inner join ride r on r.driver_id = d.id
where r.end_time2 > '2018-09-25'
and r.start_time2 < '2018-09-26';
如果在指定日期之间没有乘车,则此查询将导致
| name | sum_distance |
| ---- | ------------ |
| null | null |
但是我希望它返回一个空集。我认为这是因为在查询中使用了sum
,avg
,max
之类的聚合函数。 ride
-driver
是多对一关系。我试图以不同的方式修改查询,但仍然没有返回空集。例如:
select d.name as 'name', sum(r.distance) as 'sum_distance'
from driver d
inner join ride r on r.driver_id = d.id
where r.end_time2 > '2018-09-25'
and r.start_time2 < '2018-09-26'
and d.name IS NOT NULL;
如何解决此MySQL查询?
答案 0 :(得分:0)
Left Join
表中的driver
与第一个表一起使用。null
。由于左联接,如果在第二个表null
中找不到匹配的行,则距离值将显示为ride
。Group By
之类的聚合函数时,您应该使用Sum
。尝试以下操作:
select d.name as 'name',
sum(ifnull(r.distance,0)) as 'sum_distance'
from driver d
left join ride r on r.driver_id = d.id
where r.end_time2 > '2018-09-25'
and r.start_time2 < '2018-09-26'
group By d.name