Is querying on views slower than doing one query?

前端 未结 5 784
悲哀的现实
悲哀的现实 2020-12-19 22:47

Will Mssql be even fast when I query on a view opposed to one query?

example

When I have this view:

create view ViewInvoicesWithCustomersNam         


        
5条回答
  •  执笔经年
    2020-12-19 23:18

    Whilst in your simple example things will be the same some caution is necessary with using nested views.

    I worked on a system where queries were timing out after 30 seconds built on about 6 levels of nested views and managed to speed these up by a factor of about 100 by rewriting the queries against the base tables.

    A simple example of the type of issue that can arise is below.

    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.
    */
    

提交回复
热议问题