0

我有这个查询:

SELECT * FROM
(
SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
FROM PHONES1..TVPHONES  
UNION ALL

SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
FROM PHONES2..TVPHONES 
UNION ALL

SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
FROM PHONES3..TVPHONES
) q 
WHERE ID_CARD = 'B5XXXXXXX'

此查询需要 0.03 秒才能完成,但如果我将其转换为视图并执行相同的搜索:

ALTER VIEW [dbo].[BTPHONES]  
AS

 SELECT * FROM
    (
    SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
    FROM PHONES1..TVPHONES  
    UNION ALL

    SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
    FROM PHONES2..TVPHONES 
    UNION ALL

    SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
    FROM PHONES3..TVPHONES
    ) q 

GO

-- ------------------------

SELECT TOP 1 * FROM dbo.BTPHONES
WHERE ID_CARD = 'B5XXXXXXX'

大约需要3分钟!!为什么需要这么长时间?

计划01:

计划01

计划02:

计划02

4

1 回答 1

0

第二种情况等价于:

SELECT TOP 1 * FROM (
  SELECT * FROM
  (
    SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
    FROM PHONES1..TVPHONES  
    UNION ALL

    SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
    FROM PHONES2..TVPHONES 
    UNION ALL

    SELECT LASTNAME,NAME,STREET,PHONE,ID_CARD 
    FROM PHONES3..TVPHONES
  ) q
)
WHERE ID_CARD = 'B5XXXXXXX'

优化器可能没有意识到它可以将 where 子句应用于每个内部选择。相反,它创建整个表的联合,然后对结果进行全面扫描以应用 where 子句。

于 2013-10-11T15:24:10.783 回答