查询视图时 ,带where 条件速度过慢

今天遇到这样一个情况,通过视图查询一些字段不带where语句时很快。SQL如下

	select * ,ROW_NUMBER () OVER (ORDER BY tabs.recognisedmaori DESC) AS pos
	from( 
	SELECT
		vp.projectid id,
		vp.projectno projectno,
		vp.projectname objname,
		vp.orgname implementationdepartment,
		vp.orgid orgid,
		vp.ocontractmoney ,
		ISNULL(vp.saleIncome,0) saleIncomeBudget,
		ISNULL(vp.grossValue,0) grossValueBudget,
		vp.contractArchivingdate ,
		vp.confirmIncomeDate ,
		vp.saleman salesman,
		vp.prjmname projectmanager,
		vp.prjdirector projectdirector,
		vp.confirmIncomPer ,
		cast(ISNULL(vp.saleIncome,0) as NUMERIC(20,2))* vp.confirmIncomPer recognisedincome,
		cast(ISNULL(vp.grossValue,0) as NUMERIC(20,2)) * vp.confirmIncomPer recognisedmaori,
		vp.planFirstAccDate ,
		LEFT ( vp.planFirstAccDate, 7 ) planmoth,
		se.objname  problemType,
		act.LATESTPROGRESS latestProgress
		
	FROM
		VIEW_PROJECTMONITOR vp
		LEFT JOIN acceptanceAndReceiveT act ON act.projectid = vp.projectid
		left join selectitemlabel se on se.id = act.problemType
		
	) tabs 

大概耗时一秒左右, VIEW_PROJECTMONITOR 是视图 其他的都是表。

当添加上 where 语句时,耗时变为30多秒。SQL如下

	select * ,ROW_NUMBER () OVER (ORDER BY tabs.recognisedmaori DESC) AS pos
	from( 
	SELECT
		vp.projectid id,
		vp.projectno projectno,
		vp.projectname objname,
		vp.orgname implementationdepartment,
		vp.orgid orgid,
		vp.ocontractmoney ,
		ISNULL(vp.saleIncome,0) saleIncomeBudget,
		ISNULL(vp.grossValue,0) grossValueBudget,
		vp.contractArchivingdate ,
		vp.confirmIncomeDate ,
		vp.saleman salesman,
		vp.prjmname projectmanager,
		vp.prjdirector projectdirector,
		vp.confirmIncomPer ,
		cast(ISNULL(vp.saleIncome,0) as NUMERIC(20,2))* vp.confirmIncomPer recognisedincome,
		cast(ISNULL(vp.grossValue,0) as NUMERIC(20,2)) * vp.confirmIncomPer recognisedmaori,
		vp.planFirstAccDate ,
		LEFT ( vp.planFirstAccDate, 7 ) planmoth,
		se.objname  problemType,
		act.LATESTPROGRESS latestProgress
		
	FROM
		VIEW_PROJECTMONITOR vp
		LEFT JOIN acceptanceAndReceiveT act ON act.projectid = vp.projectid
		left join selectitemlabel se on se.id = act.problemType
		
	) tabs where tabs.orgid = '2c948148689e23db0168a234e6971853'

发现很奇怪,其中orgid 是一张基表的主键怎么会这么慢。后来在查了查我的 VIEW_PROJECTMONITOR 视图在设计的时候有问题,    其中有这么一句   isnull(org.id,”) orgid   这里用了 isnull  函数处理了orgid 使其不能在被当做索引来对待,因此查询的时候回边的很慢。

在视图中基表的主键也是索引。

如果想提高查询效率可以适当创建索引。

    原文作者:依然泛特西
    原文地址: https://blog.csdn.net/weixin_39823527/article/details/90671719
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞