gpt4 book ai didi

mysql - sql View 性能优化

转载 作者:行者123 更新时间:2023-11-29 03:00:23 24 4
gpt4 key购买 nike

我有一个具有以下定义的 View

create view mydashboard as
SELECT distinct
cu.CrimeID,
ad.DeptID,
ad.CrimeDate,
cd.DeptIncidentID,
ad.crime,
u.username
from alldatescrimes ad
inner join crimeslist cl
on
ad.crime = cl.crime
inner join users u
on
u.DeptID = ad.DeptID
left join crimelookup cu
on cu.CrimesListID = cl.CrimeListID
left join crimesdetail cd
on
ad.CrimeDate = cast(cd.CrimeDate as date)
and
ad.DeptID = cd.DeptID
and
cu.CrimeID = cd.CrimeID

我的问题是,如果我在 View 外放置一个 where 子句,查询运行会非常缓慢。看下面的例子

select *
from mydashboard
where

(username = 'john'
or
DeptIncidentID is null
)
and
CrimeDate = '2014-06-16'

相反,如果我在 View 中放置相同的 where 子句,查询将运行得非常快......大概在 2-3 秒内

我的问题是,如果我将 where 子句放在 View 之外,我可以采取什么步骤来使查询运行得更快。我在报告中使用此 View ,但查询运行速度非常慢

问候阿里夫

最佳答案

MySQL 有两个选项来处理在查询中使用的 View :MERGE or TEMPTABLE .

For MERGE, the text of a statement that refers to the view and the view definition are merged such that parts of the view definition replace corresponding parts of the statement.

For TEMPTABLE, the results from the view are retrieved into a temporary table, which then is used to execute the statement.

由于 View 定义中的DISTINCT子句,MySQL不能使用MERGE算法。它必须退回到效率较低的 TEMPTABLE 算法。

临时表没有索引,因此必须扫描整个表以处理外部 WHERE 条件。

您可能希望从 View 定义中删除 DISTINCT 子句,并将其放在您的外部查询中。

关于mysql - sql View 性能优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24633522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com