【问题标题】:Derived table used several times派生表多次使用
【发布时间】:2011-12-08 07:26:18
【问题描述】:

我需要使用同一个派生表运行 3 个连续查询...我使用的是 MS SQL Server 2008

Select a,b,c from categories inner join (select x,y,z from derivedTable where…) …
Select a,b,c from users inner join (select x,y,z from derivedTable where…) …
Select a,b,c from orders inner join (select x,y,z from derivedTable where…) …

有没有办法以派生表的方式同时运行3个sql查询

(select x,y,z from derivedTable where ...) 

只执行一次?

我使用的是 .net,所以...我想知道是否可以返回 3 个表并加载包含 3 个表的数据集。

谢谢

【问题讨论】:

  • 您使用的是哪个数据库?

标签: sql sql-server sql-server-2008 derived-table


【解决方案1】:

你可以使用WITH

注意:正如@Martin WITH 所指出的,被多次评估,因此正确的解决方案是临时表。

WITH derivedTable (x,y,z)
as
(
    select x,y,z
      from derivedTable
      ...
)
SELECT a, b, c
  FROM users
  join derivedTable on ...
 WHERE ...
union all
SELECT a, b, c
  FROM orders
  join derivedtable on ...
 WHERE ... 
union all
 ...

或临时表:

select x,y,z
  into #derivedTable
  from derivedTable
  ...

SELECT a, b, c
  FROM users
  join #derivedTable on ...
 WHERE ...
union all
SELECT a, b, c
  FROM orders
  join #derivedtable on ...
 WHERE ... 
union all
 ...

【讨论】:

  • +1 虽然是暂时的而不是暂时的。只是为了明确 CTE 将被多次评估 #temp 解决方案不会。
  • 谢谢大卫和马丁。那么,Martin,您的意思是使用“WITH derivedTable”查询会被执行多次?
  • 感谢@Martin 的更正。在西班牙语中是“暂时的”:) @user996760 是的,with 可以被评估多次。
  • @user996760 - 是的。执行计划将显示 CTE 没有预先具体化到临时表中,并且基表被多次访问。您也可以从;WITH CTE(id) AS (SELECT NEWID()) SELECT * FROM CTE c1 JOIN CTE c2 ON c1.id = c2.id 看到这一点(返回零结果)
  • @user996760:没错,derivedTable CTE 将被评估的次数与查询中引用的次数一样多。 #temp 解决方案相对于 CTE 解决方案的另一个优势(尽管在您的特定情况下可能不一定有用)是您可以在 separate 查询中使用临时表(当然,在同一范围内),而 CTE 只能在定义它的语句中访问。
猜你喜欢
  • 2016-10-15
  • 1970-01-01
  • 2013-05-26
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 2019-03-26
相关资源
最近更新 更多