请问这种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
阅读 3k
3 个回答
✓ 已被采纳

station_id这个字段添加索引

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;

后面应该有where条件的吧,针对条件加索引试试

SQL语句中规中矩,没啥了..但是可以针对数据进行优化,
比如新增一个表,用于记录station_idair_conditioning_count,cold_power_total,hot_power_total这三者的关系.

每次在表新增/修改了记录的时候,就在那个表也同步进行一下INSERT/UPDATE操作,这样数据库负担小一些,不用每次查询都这么多表联查统计,只需2个表即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏