Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

sql - Is querying on views slower than doing one query?

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

example

When I have this view:

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

What will be faster or will it be even fast?

a) select * from ViewInvoicesWithCustomersName where customerName="Bart"
b) select * from Invoices left join Customer on Customer.ID=Invoices.CustomerID
   where customername="Bart"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...