2016-04-19 56 views
0

這是我的表替代的外部應用

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服務器上執行。

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服務器中的輸出。

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

我想在MySQL中執行此操作。我想要上面提到的同樣的輸出。

+1

您正在尋求幫助!更有禮貌:) – bmsqldev

+0

我想永遠不會得到(除了SO) – Strawberry

回答

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 ; 
+0

它給出了錯誤的輸出,它給出了每個車輛的多個位置,我們希望每個車輛的頂部1位置。 – Swapnil