【SQL】1407. 排名靠前的旅行者-Code

时间:2024-03-23 18:04:05

写法一

先过滤,再连表

-- 写法一:先过滤再连表
select name, ifnull(summ, 0) as travelled_distance
from Users
left join(
    select user_id, sum(distance) as summ
    from Rides
    group by user_id
) A
on Users.id = A.user_id
order by summ desc, name asc;

写法二

先连表,再过滤

-- 写法二:先连表再过滤
select  name, ifnull(sum(distance), 0) as travelled_distance
from Users U 
left join Rides R
on U.id = R.user_id
group by R.user_id
order by travelled_distance desc, name;