如何优化复杂sql语句
原sql语句如下:
select es.id, es.station_name, es.province, es.city, es.district, es.detailed, ( select count(*) from air_conditioner_equipment where station_id = es.id ) as air_conditioning_count, ( select sum( cold_power ) from air_conditioner_equipment where station_id = es.id) as cold_power_total, ( select sum( hot_power) from air_conditioner_equipment where station_id = es.id) as hot_power_total, es.create_time, es.state from energy_station es left join user_station us on us.station_id = es.id left join user_info u on u.id = us.user_id
登录后复制
优化方法
- 添加索引
为表air_conditioner_equipment的字段station_id添加索引,可以加快根据该字段进行查询的速度。
- 使用子查询优化
优化后sql语句如下:
SELECT es.id, es.station_name, es.province, es.city, es.district, es.detailed, SUM(ace.air_conditioning_count) AS air_conditioning_count, SUM(ace.cold_power) AS cold_power_total, SUM(ace.hot_power) AS hot_power_total, es.create_time, es.state FROM energy_station es LEFT JOIN user_station us ON us.station_id = es.id LEFT JOIN user_info u ON u.id = us.user_id LEFT JOIN ( SELECT station_id, COUNT(*) as air_conditioning_count, SUM(cold_power) as cold_power, SUM(hot_power) as hot_power FROM air_conditioner_equipment GROUP BY station_id ) ace ON ace.station_id = es.id GROUP BY es.id;
登录后复制
优化后的sql语句使用子查询ace来预先计算所需的聚合值,然后再使用left join将其与主表连接。这样可以减少需要进行的子查询数量,从而提高查询效率。