SQL JOIN查询使用子查询进行优化

时间:2013-05-17 05:17:35

标签: sql postgresql query-optimization openerp

我使用下面的子查询获取附加记录。我需要知道它是我的任务的优化查询(似乎在三个月内它的存在记录超过10,000)。那么它是否支持该数据加载。?

我可以使用 JOIN 关键字代替以下方法。请建议我对此进行排序。 目前我正在使用postgresql作为我的后端。

select worker,worktype,paymenttype,sum(output)as totalkgs_ltrs,sum(overkgs)as overkgs_ltrs,sum(workedhrs) as workedhrs,sum(scrap) as scrap,sum(cashworkincome) as cashworkincome,sum(pss) as pss
from (select
  comp.name as company, 
  est.name as estate, 
  div.name as division, 
  wkr.name as worker, 
  txn.date as updateddate, 
  txn.type as worktype, 
  txn.payment_type as paymenttype, 
  txn.names as workedhrs, 
  txn.norm as norm, 
  txn.output as output, 
  txn.over_kgs as overkgs, 
  txn.scrap as scrap, 
  txn.cash_work_income as cashworkincome,
  txn.pss as pss
from 
  bpl_daily_transaction_master txn, 
  res_company comp, 
  bpl_division_n_registration div, 
  bpl_estate_n_registration est, 
  bpl_worker wkr
where 
  comp.id = txn.bpl_company_id and
  div.id  = txn.bpl_division_id and
  est.id  = txn.bpl_estate_id and
  wkr.id  = txn.worker_id
)as subq
group by worker,worktype,paymenttype

这里显示了执行此查询时的结果

refer this image

这是子查询的代码&结果标记在底部

select
  comp.name as company, 
  est.name as estate, 
  div.name as division, 
  wkr.name as worker, 
  txn.date as updateddate, 
  txn.type as worktype, 
  txn.payment_type as paymenttype, 
  txn.names as workedhrs, 
  txn.norm as norm, 
  txn.output as output, 
  txn.over_kgs as overkgs, 
  txn.scrap as scrap, 
  txn.cash_work_income as cashworkincome,
  txn.pss as pss
from 
  bpl_daily_transaction_master txn, 
  res_company comp, 
  bpl_division_n_registration div, 
  bpl_estate_n_registration est, 
  bpl_worker wkr
where 
  comp.id = txn.bpl_company_id and
  div.id  = txn.bpl_division_id and
  est.id  = txn.bpl_estate_id and
  wkr.id  = txn.worker_id

这是在主查询结果之上,它显示所有记录

refer this image

1 个答案:

答案 0 :(得分:2)

select wkr.name as worker,txn.type as worktype,txn.payment_type as paymenttype,sum(txn.output)as totalkgs_ltrs,sum(txn.over_kgs)as overkgs_ltrs,
       sum(txn.names) as workedhrs,sum(txn.scrap) as scrap,sum(txn.cash_work_income) as cashworkincome,sum(txn.pss) as pss

from 
  bpl_daily_transaction_master txn
inner join res_company comp
   on comp.id = txn.bpl_company_id 
inner join bpl_division_n_registration div
   on div.id  = txn.bpl_division_id
inner join bpl_estate_n_registration est
   on est.id  = txn.bpl_estate_id
inner join bpl_worker wkr
   on wkr.id  = txn.worker_id

group by wkr.name,txn.type,txn.payment_type

您在子查询中所做的是用于连接表的旧ANSI SQL -89语法,不建议这样做。 但就表现而言,我不认为这个stackoverflow thread确认存在差异。

  

根据Peter Gulutzan和Trudy的“SQL Performance Tuning”   Pelzer,在他们测试的六个或八个RDBMS品牌中,没有   SQL-89与SQL-92的优化或性能差异   风格加入。可以假设大多数RDBMS引擎都会转换   在优化或执行之前将语法转换为内部表示   查询,因此人类可读的语法没有区别。