Jon*_*tin 3 sql sql-server sql-optimization
所以我必须处理一个没有索引的数据库(不是我的设计,它让我感到沮丧).我正在运行一个大约需要三秒钟才能返回的查询,我需要它更快.
以下是相关的表格和列:
gs_pass_data au_entry ground_station
-gs_pass_data_id -au_id -ground_station_id
-start_time -gs_pass_data_id -ground_station_name
-end_time -comments
-ground_station_id
Run Code Online (Sandbox Code Playgroud)
我的疑问是:
SELECT DISTINCT gs_pass_data_id,start_time,end_time,
ground_station_name FROM gs_pass_data
JOIN ground_station
ON gs_pass_data.ground_station_id =
ground_station.ground_station_id
JOIN au_entry ON au_entry.gs_pass_data_id =
gs_pass_data.gs_pass_data_id
WHERE (start_time BETWEEN @prevTime AND @nextTime)
AND comments = 'AU is identified.'
ORDER BY start_time
Run Code Online (Sandbox Code Playgroud)
我尝试过使用EXISTS代替DISTINCT而没有任何改进.我已经阅读了关于SQL优化的所有内容,但我似乎无法将此查询缩短到合理的时间(合理的<0.5秒).任何想法将不胜感激.
Mar*_*c B 11
没有索引,你就被软管了.数据库引擎每次都必须进行全表扫描.摆弄查询只是重新安排泰坦尼克号上的躺椅.现在修复数据库,在数据堆积之前变得更糟.
查询也可以不用distinct 而是用group by 来编写。不过,它可能根本没有区别。标准建议与其他人的建议相同。添加索引,将 'order by' so +1 添加到 @Marc B
SELECT gs_pass_data_id,start_time,end_time,ground_station_name
FROM gs_pass_data
JOIN ground_station
ON gs_pass_data.ground_station_id = ground_station.ground_station_id
JOIN au_entry
ON au_entry.gs_pass_data_id = gs_pass_data.gs_pass_data_id
WHERE (start_time BETWEEN @prevTime AND @nextTime)
AND comments = 'AU is identified.'
GROUP BY gs_pass_data_id,start_time,end_time,ground_station_name
ORDER BY start_time
Run Code Online (Sandbox Code Playgroud)