帮我优化下这个sql : SELECT t4.vin, t3.msg_id AS trip_id, t3.trip_start_time, t4.switch_value AS has_trip FROM ( SELECT * FROM dds.dwd_driving_calendar t1 WHERE t1.vin = 'LSJA24396MS179029' AND 1681745400001 > t1.trip_start_time AND 1681745400001 < t1.trip_end_time ) t3 LEFT JOIN ( SELECT * FROM dds.vehicle_journey_switch_history t2 WHERE t2.vin IN ( 'LSJA24396MS179029' ) ) t4 ON t3.vin = t4.vin AND t4.switch_key = 'vehicle_journey_data' AND '2023-04-17 23:30:00' > t4.create_time AND '2023-04-17 23:30:00' < t4.update_time
时间: 2024-02-01 18:01:55 浏览: 70
大家来进行SQL优化
可以尝试优化以下几个方面:
1. 使用EXISTS替换LEFT JOIN
可以使用EXISTS来代替LEFT JOIN进行连接查询,因为EXISTS在查询到一条匹配的数据后就会停止,而LEFT JOIN需要查询完整个表再返回结果。
```
SELECT t3.vin, t3.msg_id AS trip_id, t3.trip_start_time,
t4.switch_value AS has_trip
FROM dds.dwd_driving_calendar t3
WHERE t3.vin = 'LSJA24396MS179029'
AND 1681745400001 > t3.trip_start_time
AND 1681745400001 < t3.trip_end_time
AND EXISTS (
SELECT 1
FROM dds.vehicle_journey_switch_history t4
WHERE t3.vin = t4.vin
AND t4.switch_key = 'vehicle_journey_data'
AND '2023-04-17 23:30:00' > t4.create_time
AND '2023-04-17 23:30:00' < t4.update_time
)
```
2. 添加索引
在vin、trip_start_time、trip_end_time、switch_key、create_time和update_time列上添加索引,可以加速查询。
3. 不要使用SELECT *
在子查询中不要使用SELECT *,而是明确指定需要查询的列,可以减少不必要的数据读取和传输,提高查询效率。例如:
```
SELECT vin, msg_id AS trip_id, trip_start_time
FROM dds.dwd_driving_calendar
WHERE vin = 'LSJA24396MS179029'
AND 1681745400001 > trip_start_time
AND 1681745400001 < trip_end_time
```
```
SELECT vin, switch_value
FROM dds.vehicle_journey_switch_history
WHERE vin IN ('LSJA24396MS179029')
AND switch_key = 'vehicle_journey_data'
AND '2023-04-17 23:30:00' > create_time
AND '2023-04-17 23:30:00' < update_time
```
阅读全文