gpt4 book ai didi

mysql - SQL Server 中外部应用的替代方法

转载 作者:行者123 更新时间:2023-11-29 11:35:59 25 4
gpt4 key购买 nike

我在 SQL Server 中有一个查询,其中我使用了外部应用。现在我想对其进行转换,以便查询也可以在 SQL Server 和 MySQL 上运行。

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

我必须隐藏此查询,以便可以在两个数据库上运行。

这是我的 table

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 中的输出。

<表类=“s-表”><标题>车辆编号位置 <正文>MH14 aa 1111aaaMH12 bb 2222cccMH13 cc 3333eeeMH42 dd 4444ggg

我想在 MySQL 中执行这个。我想要与上面提到的相同的输出。

最佳答案

在这种情况下,您可以使用 LEFT JOIN 而不是 OUTER APPLY。像这样:

select top 5 v.sVehicleName as VehicleNo, ll.Location 
from vehicles v
left join
(
select vehicle_id, min(Location) as Location
from location_history
group by vehicle_id
) ll
on ll.vehicle_id = v.vehicle_id

关于mysql - SQL Server 中外部应用的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36589974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com