简体   繁体   English

SQL Server:加入2个查询,性能问题

[英]SQL Server : join 2 queries, performance issue

I have two (rather complex) functions which both return a table; 我有两个(相当复杂)的函数,它们都返回一个表。

(SELECT Id, x, y FROM fnGetXY(3)) (execution takes +/- 5 sec)

(SELECT Id, a, b FROM fnGetAB(3)) (execution takes +/- 15 sec)

I want to combine the result; 我想结合结果;

SELECT X.Id, x, y, a, b FROM 
(
 (SELECT Id, x, y FROM fnGetXY(3)) X
 JOIN (SELECT Id, a, b FROM fnGetAB(3)) Y ON X.Id=Y.Id
)

The result is correct, however this does not take the expected +/- 20-25 seconds, but 90 seconds. 结果是正确的,但是这不会花费预期的+/- 20-25秒,而是90秒。

Is there any way I can force a combination of the results of the two queries in a way that consumes maximum slightly more than the sum of each? 有什么办法可以使两个查询的结果组合起来,使之消耗的最大值比每个查询的总和稍微多一点?

[Update] [更新]

  1. #temp; #TEMP; As this is part of a function, a #temp table is not an option unfortunately. 由于这是函数的一部分,因此不幸的是#temp表不是一个选项。
  2. I have tried LEFT JOIN instead of JOIN with no result, but it appears that FULL OUTER JOIN solves this case.. 我尝试了LEFT JOIN而不是JOIN, 没有结果, 看来FULL OUTER JOIN解决了这种情况。

Thanks everybody! 谢谢大家!

In most cases the solution is to save the intermediate results into #temp tables and then join the results: 在大多数情况下,解决方案是将中间结果保存到#temp表中,然后将结果合并:

select Id, x, y
into #t1
from fnGetXY(3)

select Id, a, b 
into #t2
from fnGetAB(3)

SELECT #t1.Id, x, y, a, b 
FROM #t1
INNER JOIN #t2 on #t1.id = #t2.id

SQL Server optimizer doesn't like dealing with functions very much (except the inline TVFs). SQL Server优化器不太喜欢处理函数(内联TVF除外)。

You should be able to JOIN these two functions as you would join two table, I think these sub-queries are just an overkill of a fairly simple query. 您应该能够像联接两个表一样联接这两个函数,我认为这些子查询只是一个相当简单的查询的过大杀伤力。 Try something like .... 试试....

SELECT t1.Id
     , t1.x
     , t1.y
     , t2.a 
     , t2.b 
FROM fnGetXY(3) t1 INNER JOIN fnGetAB(3) t2
ON t1.Id = t2.Id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM