[英]how to optimize below SQL query?
I want to find an entity name that could be in one of the six tables. 我想找到一个可能在六个表之一中的实体名称。 For that I have written a function
getEntityName(entityid)
. 为此,我编写了一个函数
getEntityName(entityid)
。 The code is working fine as I am using UNION
for the tables. 由于我在表中使用
UNION
,因此代码工作正常。 But the problem is, these tables contain a huge amount data so the function is taking a long time to return the output. 但是问题是,这些表包含大量数据,因此该函数需要很长时间才能返回输出。 I am not sure if by using
JOIN
I can optimize this function. 我不确定是否可以通过使用
JOIN
来优化此功能。 I am sharing the function definition; 我正在共享函数定义; please let me know if there is any way to optimize this function:
请让我知道是否有任何方法可以优化此功能:
delimiter $$
drop function if exists getEntityName$$
create function getEntityName(entityid int) returns varchar(128)
begin
return(
select
shortname as entityname
from partnerships
where partnerships.pshipentid = entityid
union
select
concat(lastname, ', ', firstname) as entityname
from individuals
where individuals.indentid = entityid
union
select
shortname as entityname
from firms
where firms.firmentid = entityid
union
select
shortname as entityname
from funds
where funds.fundentid = entityid
union
select
entityshortname as entityname
from deletedentities
where deletedentities.entityid = entityid
);
end$$
There's nothing too much wrong with the queries in the function or the unions
函数或
unions
的查询没有什么错
However, it is critical to the performance that the following indexes exist: 但是,存在以下索引对于性能至关重要:
The other probable issue is that if the function is evaluated over a large set of data, it will be evaluated one row at a time, eg 另一个可能的问题是,如果对大量数据评估函数,则一次将评估一行,例如
select getEntityName(firms.id)
from firms;
In this case, a set based approach would be preferable. 在这种情况下,基于集合的方法将是更可取的。 MySql doesn't have Table Valued Parameters (ie you can't pass a bunch of entityid's into the function), but there are other workarounds .
MySql没有表值参数(即您不能将一堆entityid传递给函数),但是还有其他解决方法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.