今天接到客户反馈,网站这两天经常出现无法访问的情况,查看日志发现是一个页面里的SQL查询太慢,需要30多秒导致超时并且因为访问量多堵塞住了,导致其他页面也无法正常访问,所以对这个sql进行优化,下面介绍下优化过程。
这个查询是通过3个表来查询的,一个产品表(prod),两个别名表(synonym,synonym_cn),原来的sql语句是这样的:
select id from prod where prod.id > 0 and (prod.cas = '72-44-6' or (exists (select 1 from synonym where prod.id = synonym.prod and lower(synonym.name) = '72-44-6')) or(exists (select 1 from synonym_cn where prod.id = synonym_cn.prod and lower(synonym_cn.name) = '72-44-6')))
其中prod.cas建了唯一索引,synonym和synonym_cn的name建了lower函数索引。prod的数量是64万,synonym和synonym_cn都是100多万。
分析后发现prod.cas并没有走索引,所以先去掉cas的查询条件进行测试,发现还是很慢,而name的搜索还会结合prod.id,所以重建了synonym和synonym_cn的name索引为联合索引,即prod和lower(name),但测试后效果依然不理想,所以讲索引改回,并将语句分成三个语句测试:
select id from prod where prod.cas = '72-44-6'
select prod from synonym where lower(synonym.name) = '72-44-6'
select prod from synonym_cn where lower(synonym_cn.name) = '72-44-6'
发现搜索速度都很快,所以讲整体语句改成
select id from prod where prod.id in (select b.id from prod b where b.cas = '72-44-6' union select prod from synonym where lower(synonym.name) = '72-44-6' unionselect prod from synonym_cn where lower(synonym_cn.name) = '72-44-6')
至此解决问题。
原文链接:https://www.f2er.com/postgresql/194580.html