帮我优化SQL:SELECT b.DeviceName as '设备名称' ,a.[CurDeviceNO] as '设备编号',a.[CurWOID] as '当前工单ID' ,case c.IsStartBtnClick when 1 then '运行中' when 0 then '停止' end as '当前状态' ,c.LastTime as '状态切换时间' FROM [InjectionStation].[dbo].[CurWOINFO] a inner join MES_DB_Utility.dbo.StationDevices b on a.CurDeviceNO=b.DeviceID inner join ( select Temp.[CurDeviceNo],Temp.LastTime,b.IsStartBtnClick from (SELECT a.[CurDeviceNo] ,Max([ClickStartBtnOrStopTime]) as 'LastTime' FROM [InjectionStation].[dbo].[CurAddOnProLine] a where a.CurDeviceNo in (select distinct [CurDeviceNO] from [InjectionStation].[dbo].[CurWOINFO]) group by a.[CurDeviceNo]) Temp inner join [InjectionStation].[dbo].[CurAddOnProLine] b on Temp.LastTime=b.ClickStartBtnOrStopTime and Temp.CurDeviceNo=b.CurDeviceNo) c on a.CurDeviceNO=c.CurDeviceNo
时间: 2024-04-08 19:29:18 浏览: 54
根据您提供的SQL语句,我注意到您使用了子查询来获取最近的状态切换时间。虽然这是一种有效的方法,但可能会对查询性能产生一定的影响。我建议您尝试使用窗口函数来优化查询,以避免使用子查询。
以下是优化后的SQL语句:
```
SELECT b.DeviceName AS '设备名称',
a.CurDeviceNO AS '设备编号',
a.CurWOID AS '当前工单ID',
CASE c.IsStartBtnClick WHEN 1 THEN '运行中' WHEN 0 THEN '停止' END AS '当前状态',
c.LastTime AS '状态切换时间'
FROM [InjectionStation].[dbo].[CurWOINFO] a
INNER JOIN MES_DB_Utility.dbo.StationDevices b ON a.CurDeviceNO = b.DeviceID
INNER JOIN (
SELECT a.CurDeviceNo,
b.IsStartBtnClick,
b.LastTime,
ROW_NUMBER() OVER (PARTITION BY a.CurDeviceNo ORDER BY b.ClickStartBtnOrStopTime DESC) AS rn
FROM [InjectionStation].[dbo].[CurAddOnProLine] a
INNER JOIN [InjectionStation].[dbo].[CurAddOnProLine] b ON a.CurDeviceNo = b.CurDeviceNo
WHERE a.CurDeviceNo IN (SELECT DISTINCT [CurDeviceNO] FROM [InjectionStation].[dbo].[CurWOINFO])
) c ON a.CurDeviceNO = c.CurDeviceNo AND c.rn = 1
```
在优化后的查询中,我使用了窗口函数 `ROW_NUMBER()` 来标记每个设备的状态切换记录,并根据最近的时间排序。然后,通过在主查询中添加 `c.rn = 1` 的条件来获取每个设备的最新状态切换记录。
请注意,优化的查询可能需要根据您的数据库结构和数据量进行调整和测试,以确保性能得到提升。
阅读全文