0

我有以下查询,但它在我的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)
4

3 回答 3

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(*),但总是选择我希望计算的列。

于 2013-04-29T08:29:15.687 回答
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)将有所帮助

于 2013-04-29T08:29:31.160 回答
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)吗?
  • 是否有索引 onGK_main (year, father_code)或 on GK_main (father_code, year)
  • 是否有索引 onGK_main (year, main_code)或 on GK_main (main_code)
于 2013-04-29T10:10:37.117 回答