例如,我有这个order
表,它有列:order_id,user_id,create_time,city_id。
现在我想要输入用户最近的订单,所以基本上我想做的是:
select distinct(order.user_id), city_id
from order
where city_id != 0
order by create_time desc
但据我所知distinct
将在order by
之前运行,这意味着每个用户在到达user_id
之前只剩下一个order by
,那么做什么呢?我要先让order by
跑?
答案 0 :(得分:1)
有一个子查询返回每个用户最近的create_time。结果为JOIN
。
select o1.user_id, o1.city_id
from order o1
join (select user_id, max(create_time) as newest_create_time
from order
where city_id != 0
group by user_id) o2
on o1.user_id = o2.user_id and o1.create_time = o2.newest_create_time
where o1.city_id != 0