优化SQL语句SELECT * FROM ( SELECT d.driver_id, d.driver_name, v.numberplate, v.vehicle_type, d.driver_photo, d.phone_number, ( SELECT count( 1 ) FROM waybill_info WHERE transport_status<>9 and driver_id = d.driver_id ) AS transportStatus FROM driver_info AS d INNER JOIN driver_vehicle_bind AS d1 ON d.driver_id = d1.driver_id INNER JOIN vehicle_info AS v ON d1.vehicle_id = v.vehicle_id WHERE d1.is_use = 1 AND d1.bind_status = 1 AND v.cert_status = 1 AND d.cert_status = 2 ) AS s WHERE s.driver_id NOT IN ( SELECT driver_id FROM collect_blacklist WHERE user_id = #{userId})
时间: 2024-02-14 08:35:20 浏览: 140
关于SQL语句的优化
可以尝试对该SQL语句进行以下优化:
1. 减少不必要的列查询:在SELECT语句中只选择需要的列,而不是使用通配符*,可以减少数据传输量,提高查询效率。
2. 使用JOIN代替子查询:在内部查询中使用JOIN语句代替子查询,可以提高查询效率。因为JOIN语句可以将多个表的数据一次性查询出来,而子查询会多次查询。
3. 使用EXISTS代替IN:在外部查询中使用EXISTS代替IN,可以提高查询效率。因为EXISTS只需要判断是否存在符合条件的记录,而IN需要先查询出符合条件的所有记录。
下面是优化后的SQL语句:
SELECT d.driver_id, d.driver_name, v.numberplate, v.vehicle_type, d.driver_photo, d.phone_number, count(w.waybill_id) AS transportStatus
FROM driver_info d
INNER JOIN driver_vehicle_bind d1 ON d.driver_id = d1.driver_id
INNER JOIN vehicle_info v ON d1.vehicle_id = v.vehicle_id
LEFT JOIN waybill_info w ON w.driver_id = d.driver_id AND w.transport_status <> 9
WHERE d1.is_use = 1
AND d1.bind_status = 1
AND v.cert_status = 1
AND d.cert_status = 2
AND NOT EXISTS (
SELECT 1
FROM collect_blacklist
WHERE driver_id = d.driver_id
AND user_id = #{userId}
)
GROUP BY d.driver_id, d.driver_name, v.numberplate, v.vehicle_type, d.driver_photo, d.phone_number
ORDER BY d.driver_id;
注意,优化SQL时需要根据具体情况进行选择和应用,以上仅供参考。
阅读全文