请问这种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
回答:
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_id
与air_conditioning_count
,cold_power_total
,hot_power_total
这三者的关系.
每次在表新增/修改了记录的时候,就在那个表也同步进行一下INSERT
/UPDATE
操作,这样数据库负担小一些,不用每次查询都这么多表联查统计,只需2个表即可
以上是 请问这种sql能够优化吗? 的全部内容, 来源链接: utcz.com/p/944937.html