是一个

select *  from myView

比查询本身更快地创建视图(为了拥有相同的resultSet):

select * from ([query to create same resultSet as myView])

?

我不完全清楚视图是否使用了某种缓存,使其比简单查询更快。


当前回答

In SQL Server at least, Query plans are stored in the plan cache for both views and ordinary SQL queries, based on query/view parameters. For both, they are dropped from the cache when they have been unused for a long enough period and the space is needed for some other newly submitted query. After which, if the same query is issued, it is recompiled and the plan is put back into the cache. So no, there is no difference, given that you are reusing the same SQL query and the same view with the same frequency.

显然,在一般情况下,一个视图,根据它的本质(有人认为它被经常使用,使它成为一个视图)通常比任何任意的SQL语句更有可能被“重用”。

其他回答

视图的目的是一遍又一遍地使用查询。为此,SQL Server、Oracle等通常会提供视图的“缓存”或“编译”版本,从而提高其性能。一般来说,这应该比“简单”查询执行得更好,但如果查询确实非常简单,好处可能可以忽略不计。

现在,如果您正在执行一个复杂的查询,请创建视图。

我的理解是,在过去,视图会更快,因为SQL Server可以存储执行计划,然后直接使用它,而不是试图在飞行中找出一个。我认为现在的性能增益可能没有以前那么大,但我不得不猜测使用视图会有一些边际改进。

对于SQL Server来说,视图肯定比嵌套查询要好。在不知道为什么它更好的情况下(直到我读到Mark Brittingham的文章),我已经运行了一些测试,在使用视图和嵌套查询时,我经历了几乎惊人的性能提升。在连续运行查询的每个版本数百次之后,查询的视图版本在一半的时间内完成。我得说这对我来说已经足够了。

出乎意料的是,在某些情况下,视图会慢得多。

我最近发现这一点,当我有问题的数据,从甲骨文需要按摩成另一种格式。也许有2万行源行。一张小桌子。为此,我们尽可能地将oracle数据导入到一个表中,然后使用视图提取数据。 我们在这些观点的基础上提出了次要观点。可能有3-4层视图。

最后一个查询可能提取了200行,需要45分钟以上!该查询基于视图级联。可能有3-4层深。

我可以使用每个视图,将其sql插入到一个嵌套查询中,并在几秒钟内执行它。

我们甚至发现,我们甚至可以将每个视图写入临时表和查询,以代替视图,这仍然比简单地使用嵌套视图快得多。

更奇怪的是,性能一直很好,直到我们达到了将源行拉入数据库的限制,性能在几天内急剧下降——只需要多几行源行就可以了。

因此,使用从视图中提取的查询比嵌套查询慢得多,这对我来说毫无意义。

一般来说,没有。视图主要用于方便和安全,(它们本身)不会带来任何速度上的好处。

也就是说,SQL Server 2000及以上版本确实有一个称为索引视图的特性,可以极大地提高性能,但有一些注意事项:

不是每个视图都可以被做成索引视图;它们必须遵循一组特定的指导方针,这(在其他限制中)意味着您不能包含常见的查询元素,如COUNT、MIN、MAX或TOP。 索引视图使用数据库中的物理空间,就像表上的索引一样。

本文描述了索引视图的其他优点和局限性:

You Can… The view definition can reference one or more tables in the same database. Once the unique clustered index is created, additional nonclustered indexes can be created against the view. You can update the data in the underlying tables – including inserts, updates, deletes, and even truncates. You Can’t… The view definition can’t reference other views, or tables in other databases. It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other keywords or elements. You can’t modify the underlying tables and columns. The view is created with the WITH SCHEMABINDING option. You can’t always predict what the query optimizer will do. If you’re using Enterprise Edition, it will automatically consider the unique clustered index as an option for a query – but if it finds a “better” index, that will be used. You could force the optimizer to use the index through the WITH NOEXPAND hint – but be cautious when using any hint.