I have a query in SQL server in which I have used outer apply. Now I want to convert it so that query can run on SQL server and MySQL also.
select top 5 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
I have to covert this query so I can run on both databases.
This is my tables
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())
This is query which I execute in 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
This is output in SQL server.
VehicleNo | Location |
---|---|
MH14 aa 1111 | aaa |
MH12 bb 2222 | ccc |
MH13 cc 3333 | eee |
MH42 dd 4444 | ggg |
I want to execute this in MySQL. and I want same output mentioned above.