首页 文章

查询视图的速度比执行一个查询要慢吗?

提问于
浏览
3

当我查询与一个查询相反的视图时,Mssql会更快吗?

当我有这个观点时:

create view ViewInvoicesWithCustomersName
Select * from Invoices left join Customer on Customer.ID=Invoices.CustomerID

什么会更快还是会更快?

a) select * from ViewInvoicesWithCustomersName where customerName="Bart"
b) select * from Invoices left join Customer on Customer.ID=Invoices.CustomerID
   where customername="Bart"

5 回答

  • 3

    虽然在您的简单示例中,使用嵌套视图时需要注意一些事项 .

    我在一个系统上工作,在大约6级嵌套视图构建30秒后查询超时,并设法通过重写基表的查询来加快这些速度约100倍 .

    下面是可能出现的问题类型的简单示例 .

    CREATE VIEW MaxTypes
    AS
    SELECT
      [number],
      MAX(type) AS MaxType
      FROM [master].[dbo].[spt_values]
    GROUP BY [number]
    
    GO
    
    CREATE VIEW MinTypes
    AS
    SELECT
      [number],
      MIN(type) AS MinType
      FROM [master].[dbo].[spt_values]
    GROUP BY [number]
    
    GO
    SET STATISTICS IO ON
    
    SELECT     MaxTypes.number, MinTypes.MinType, MaxTypes.MaxType
    FROM         MinTypes INNER JOIN
                          MaxTypes ON MinTypes.number = MaxTypes.number
    ORDER BY MaxTypes.number
    
    /*
    Gives
    
    Table 'spt_values'. Scan count 2, logical reads 16, physical reads 0, 
    read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    */
    GO
    
    SELECT 
      [number],
      MAX(type) AS MaxType,
      MIN(type) AS MinType
      FROM [master].[dbo].[spt_values]
    GROUP BY [number]
    ORDER BY  [number]
    
    /*
    Gives
    
    Table 'spt_values'. Scan count 1, logical reads 8, physical reads 0, 
    read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    */
    

    enter image description here

  • 2

    视图只是一个扩展/取消嵌入主查询的宏 . 所以这些是等价的 .

    注意:如果customername在Customer表中,那么您需要在没有客户的情况下开具发票和发票:

    select
      *
    from
      Invoices
      left join
      Customer on Customer.ID=Invoices.CustomerID and customername="Bart"
    
  • 2

    两个查询都是等价的 .

  • 2

    它们是相同的,但查看执行计划,以便您可以看到正在发生的事情 . 如果您遇到性能问题,则可能需要索引 . 假设 Customer.ID 是具有聚簇索引的主键,则 Invoice.CustomerIDCustomerName 是索引的良好候选者 .

  • 4

    两者都应该几乎相同的时间 .

    这里的视图只是表示在访问View时要为数据执行的查询 .

    还有另一种类型的视图,即 Materialized View . 这种类型的视图具有物理存在性 . 并且在访问此类视图时不执行查询(在视图创建期间传递) . 从这种类型的观点中获取应该更快 .

相关问题