如何增强嵌套查询的性能?

时间:2013-04-29 08:22:18

标签: sql performance tsql informix

我有以下查询,但它在sql editor中运行缓慢! 如何增强它(写明文)以加快查询运行速度。


SELECT year,main_code,name,father_code,main_code || '__' || year AS main_id, 
(SELECT COUNT(*) FROM GK_main 
WHERE father_code=sc.main_code AND 
year= (SELECT MAX(year)FROM SS_job)) childcount
FROM GK_main sc WHERE year=(SELECT MAX(year)FROM SS_job)

3 个答案:

答案 0 :(得分:1)

使用连接而不是子查询。

SELECT sc.year,sc.main_code,sc.name,sc.father_code,sc.main_code || '__' || sc.year AS main_id, 
COUNT(F.father_code) AS childcount
FROM GK_main sc LEFT JOIN GK_main F ON F.father_code = sc.main_code
WHERE year=(SELECT MAX(year)FROM SS_job)
GROUP BY sc.year,sc.main_code,sc.name,sc.father_code

未经过测试并快速完成,因此可能包含错误。但至少应该避免两次检查SELECT MAX(year)FROM SS_job。

我永远不会做COUNT(*),但总是选择我想要的柱子。

答案 1 :(得分:1)

尝试此查询

SELECT 
   year,
   main_code,
   name,
   father_code,
   main_code || '__' || year AS main_id, 
   childcount.cnt as 'count'
FROM 
   GK_main sc 
LEFT JOIN
   (SELECT 
       father_code, 
       COUNT(*) AS cnt 
   FROM 
       GK_main 
   WHERE 
       year= (SELECT MAX(year)FROM SS_job) 
   GROUP BY 
       father_code) childcount
ON childcount.father_code = sc.main_code

(father_code, year)上创建有助于

的必要索引

答案 2 :(得分:1)

效率更多地取决于可用的索引,而不是它的编写方式。您可以尝试此版本(没有内联子查询):

SELECT 
    sc.year,
    sc.main_code,
    sc.name,
    sc.father_code,
    sc.main_code || '__' || sc.year AS main_id, 
    NVL(g.childcount, 0) AS childcount
FROM 
    GK_main sc
  LEFT JOIN
    ( SELECT father_code ,
             COUNT(*) AS childcount
      FROM GK_main 
      WHERE year = (SELECT MAX(year) FROM SS_job)
      GROUP BY father_code
    ) AS g
      ON g.father_code = sc.main_code 
WHERE 
    sc.year = (SELECT MAX(year) FROM SS_job) ;

但是效率的好处是指数。

  • SS_job (year)上有索引吗?
  • GK_main (year, father_code)GK_main (father_code, year)上有索引吗?
  • GK_main (year, main_code)GK_main (main_code)上有索引吗?