我的查询
SELECT unnest(array [repgroupname,repgroupname||'-'
||masteritemname,repgroupname||'-' ||masteritemname||'-'||itemname]) AS grp
,unnest(array [repgroupname,masteritemname,itemname]) AS disp
,groupname1
,groupname2
,groupname3
,sum(qty) AS qty
,sum(freeqty) AS freeqty
,sum(altqty) AS altqty
,sum(discount) AS discount
,sum(amount) AS amount
,sum(stockvalue) AS stockvalue
,sum(itemprofit) AS itemprofit
FROM (
SELECT repgroupname
,masteritemname
,itemname
,groupname1
,groupname2
,groupname3
,units
,unit1
,unit2
,altunits
,altunit1
,altunit2
,sum(s2.totalqty) AS qty
,sum(s2.totalfreeqty) AS freeqty
,sum(s2.totalaltqty) AS altqty
,sum(s2.totaltradis + s2.totaladnldis) AS discount
,sum(amount) AS amount
,sum(itemstockvalue) AS stockvalue
,sum(itemprofit1) AS itemprofit
FROM sales1 s1
INNER JOIN sales2 s2 ON s1.txno = s2.txno
INNER JOIN items i ON i.itemno = s2.itemno
GROUP BY repgroupname
,masteritemname
,itemname
,groupname1
,groupname2
,groupname3
,units
,unit1
,unit2
,altunits
,altunit1
,altunit2
ORDER BY itemname
) AS tt
GROUP BY grp
,disp
,groupname1
,groupname2
,groupname3
这里
Sales1 table have 144513 Records
Sales2 Table have 438915 Records
items Table have 78512 Records
此查询需要6秒才能生成结果。
如何优化此查询?
我正在使用postgresql 9.3
答案 0 :(得分:0)
这是一个真正可怕的问题。
您应该首先在子选择中丢失ORDER BY - 外部查询将丢弃排序。
除此之外,问问自己为什么你需要查看DBMS中每个歌曲行的摘要 - 这是否有用(如果查询返回超过20行,则答案为否)。< / p>
您可以通过确保表中的外键被编入索引来使其更快(索引是您在谈论性能时所看到的最重要的信息,并且您已经我们没有告诉他们)。
将查询维护为常规快照可以减轻性能影响。