外部申请的替代方案

时间:2016-04-19 10:49:51

标签: mysql sql sql-server left-join outer-apply

这是我的表

create table #vehicles (vehicle_id int, sVehicleName varchar(50))

create table #location_history ( vehicle_id int, location varchar(50), date datetime)

insert into #vehicles values
    (1, 'MH 14 aa 1111'),
    (2,'MH 12 bb 2222'),
    (3,'MH 13 cc 3333'),
    (4,'MH 42 dd 4444')

insert into #location_history values
    ( 1, 'aaa', getdate()),
    ( 1, 'bbb' , getdate()),
    ( 2, 'ccc', getdate()),
    ( 2, 'ddd', getdate()),
    (3, 'eee', getdate()),
    ( 3, 'fff', getdate()),
    ( 4, 'ggg', getdate()),
    ( 4 ,'hhh', getdate())

这是我在SQL server中执行的查询。

select v.sVehicleName as VehicleNo, ll.Location
from #vehicles v outer APPLY
     (select top 1 Location from #location_history where vehicle_id = v.vehicle_id
     ) ll

这是在SQL server中输出的。

  VehicleNO|Location
MH14aa1111 |  aaa
MH12bb2222 | ccc
MH13cc3333 | eee
MH42dd4444  |ggg

我想在MySQL中执行此操作。我想要上面提到的相同输出。

1 个答案:

答案 0 :(得分:2)

首先,SQL Server查询实际上没有意义,因为您使用的top没有order by

据推测,你打算这样:

select v.sVehicleName as VehicleNo, ll.Location
from #vehicles v outer APPLY
     (select top 1 Location
      from #location_history
      where vehicle_id = v.vehicle_id
      order by ??  -- something to indicate ordering
     ) ll;

您需要一种方法来获取每辆车的最新记录。在正常情况下,我认为date会包含此信息 - 但是,在您的示例数据中并非如此。

假设date确实包含唯一值,那么您可以这样做:

select v.sVehicleName as VehicleNo, ll.Location
from vehicles v join
     location_history lh
     using (vehicle_id)
where lh.date = (select max(lh2.date)
                 from location_history lh2
                 where lh2.vehicle_id = lh.vehicle_id
                );

否则,您可以使用相关子查询执行所需操作。但是,这将在最近的日期返回任意匹配值:

select v.sVehicleName as VehicleNo,
       (select ll.Location
        from location_history lh2
        where lh2.vehicle_id = lh.vehicle_id
        order by date desc
        limit 1
       ) as location
from vehicles v ;