【发布时间】:2019-01-14 07:39:41
【问题描述】:
我有两张表,一张用于某种设备,另一张用于它们的位置(使用此表来记录位置历史记录)。表的架构是:
-
tbl_Devices:
- DeviceSrNumber (bigint, not null, pk)
- 其他一些列
-
tbl_DeviceLocation
- SrNumber(bigint,not null,pk,identity)
- DeviceSrNumber(bigint,非空)
- 位置(varchar(300),非空)
- AddDateTime(日期时间,非空)
我需要的是DeviceSrNumber,最后一个Location,最后一个位置集AddDateTime
我现在在做什么:
SELECT
DeviceSrNumber,
(
SELECT TOP (1) Location
FROM tbl_DeviceLocation
WHERE (DeviceSrNumber = d.DeviceSrNumber)
ORDER BY AddDateTime DESC
) AS 'Location',
(
SELECT TOP (1) AddDateTime
FROM tbl_DeviceLocation
WHERE (DeviceSrNumber = d.DeviceSrNumber)
ORDER BY AddDateTime DESC
) AS 'AddDateTime '
FROM
tbl_Devices AS d
但我需要以更简洁的方式使用连接,因为据我所知,子查询效率不高,不推荐在大型数据库中使用。
注意:它只是大型项目的一小部分,将处理数百万条记录。
【问题讨论】:
-
你有
Indexestbl_DeviceLoation吗? -
是的。我在 SrNumber 上有聚集索引(bigint,not null,identity,PK)并且还检查了“Location”列。但这和我们的问题有关系吗?
-
CHECK是 约束 而不是 INDEX,因此您只有一个索引。 -
子查询性能取决于查询和优化器。与每个优化问题一样,应该在实践中衡量它和其他选项。当然,对于特定的实现,有记录和观察/假设的趋势——在这里,我们可以怀疑某些重复的代码可能没有得到很好的优化,并可能通过连接来寻求 tbl_DeviceLocation 的单一提及。你是怎么尝试的? PS 通过后期编辑进行澄清,而不是 cmets。另外对于代码问题,请提供minimal reproducible example。
标签: sql-server join subquery query-performance sqlperformance