Sql语句:
select count(s.fuid) amount,case when avg(s.grade) is null then 0 else round(avg(s.grade)*20,2) end average,b.name,b.lon,b.lat
from bs_hotel b left join dwd_comment_hotel_sentiment_internet_spider s
on b.name = s.dpkeyword group by b.name
问题:
联表查询使用left join,查询时间4s左右,使用explain查看,possible keys中有,但是key为空,说明并没有使用索引。
取消left join,改用where查询测试,时间1s左右,key中两个表的索引都有使用。
查询所得:
1、当where条件中存在右表的非空条件时(is null 除外),left join失效,查询结果和时效等同于join和where。
参考:https://www.cnblogs.com/weizhenlu/p/5970392.html
2、当两表的关联字段排序规则不一致时,left join查询不走索引。
参考:https://www.cnblogs.com/jarjune/articles/7912722.html
解决:
where条件中没有右表的条件,将两张表的关联字段排序规则统一,最后的查询时间从4.6s优化至0.22s