我想查询出每一个货单最后更新的那条数据。一个货id对应一条数据
结果集包含的字段
orderId userName status updateTime
SQL查询
分享到:
------解决方案--------------------
select
a.id as orderId,
b.userName,
c.status,
c.updateTime
from
Orders as a,Users as b,OrdersLog as c
where
a.id=c.orderId and b.id=c.userId
and
not exists(select 1 from OrdersLog where OrdersLog=c.OrdersLog and updateTime>c.updateTime)
------解决方案-------------------- select orderId,userName, status, updateTime from
(select *,rn=row_number() over (partition by orderid order by updatetime desc) from orderslog) a,users
where a.userid=b.userid and rn='1' ------解决方案-------------------- try this, It 's better have an index on OrdersLog(orderId).
select a.orderId,b.userName,a.status,a.updateTime
from OrdersLog a
inner join Users b on a.userId=b.id
inner join
(select orderId,max(id) 'maxid'
from OrdersLog
group by orderId) c on a.orderId=c.orderId and a.id=c.maxid