有两个不一样的表,A表是基础数据,B表根据A表的某个不重复关键字加其余一些条件查询出一条或几条数据,取其中一条数据。而且利用此数据某个关键字再在B表中查询下一层级数据,最终将A表的对应一条数据,B表查询出的两条数据拼成一条数据返回。sql
因为这个联合查询的结果用的频次与量都很大,因此作成了view,一开始是使用function来控制leftjoin条件筛选数据与匹配。可是如果把function做为条件,整个sql语句的查询效率不好,在每次执行查询都须要3s左右。对系统的运行速度与稳定行都产生了必定的影响。bash
在优化中考虑的就是去除sql中的function,可是在function中能够很方便的进行判断与错误处理,能够避免因为数据问题致使整个view没法使用。将function改为sql就要考虑到数据多或少的状况下如何保证准确性。因为业务要求能够知足,因此最终的sql中A表只执行匹配0条或者1条B表中的数据。 最终代码以下函数
CREATE OR REPLACE VIEW ERP_MPS_PROCESS AS
SELECT distinct *
FROM SAP_ITEM_DIE T --A表
left join (select h.parent_code,
max(h.component_code) as component_code,
h.werks,
h.stktx
from ERP_BOM h --B表
left join erp_product_details j
on h.component_code = j.item_code
and h.werks = j.dept_code
where j.material_type = 'Z350'
group by h.parent_code, h.werks, h.stktx) k
on k.parent_code = T.MTNR1
and k.stktx = t.equnr
left join (select m.parent_code, max(m.component_code) as refcode
from ERP_BOM m --B表第二次取值
left join erp_product_details n
on m.component_code = n.item_code
and m.werks = n.dept_code
where n.material_type = 'Z300'
group by m.parent_code) o
on o.parent_code = k.component_code
;
复制代码
利用max函数保证取出的数据不超过一条,再利用对应条件与left join替代function的功能。优化
在使用了替代方案后,总体查询时间在0.1s到0.2s中,相对于本来3s有了很大的提高,固然,此方法仍有优化的空间,哪位有更好的方法也请不吝赐教。ui