This question is about database views, not materialized-views.
Pros:
- Query simplification.
- Avoid repeat the same joins on multiples queries.
- Avoid magic numbers.
Cons:
- Hiding real queries (may be you are repeating joins).
What else?
This question is about database views, not materialized-views.
Pros:
Cons:
What else?
Pros: Allows you to change the underlying data structures without affecting the queries applications are using (as long as your view can hide the data structures)
Security. Grant access on a view to the users who should be able to see the columns returned from it.
Views are pretty awesome when you don't entirely trust the party sending queries to your database. A good example might be you would create a view on tables for a contractor so that all they can see is the rows pertaining to their project.
尽管视图可以隐藏复杂性和多个连接,但无论如何这些都是 SP 中的复杂性。
如果可以优化 SP,则应该优化视图,这将提高所有命中该视图的 SP 的性能。
视图非常强大和有用,原因之一是在所有其他非常好的原因中脱颖而出。它们减少了代码重复。也就是说,在大多数情况下,底线。如果查询将在三个或更多地方使用,那么如果架构或查询参数发生更改,视图将大大简化您的更改。
我曾经不得不编辑 22 个存储过程来更改一些查询逻辑。如果原始架构使用视图,那么我将只有三个更改。
现在 SQL Server 具有公用表表达式,我发现自己创建的视图更少。当我创建一个视图时,它通常是用于可用于许多查询的规范化层次结构,而不是替代一个查询的东西。
例如 Region、Market 和 City 可能是三个标准化表(雪花)。我 90% 的查询都需要这些数据,所以我将创建一个视图。该视图永远不会替换单个查询,而是使所有其他查询变得简单和干燥。
我不得不多次使用视图来进行奇怪的连接和按别名分组。
通过奇怪的连接,我的意思是选择一个不同日期的列表,然后将它们外部连接到它们来自的表中,以获得空天的空条目。我想不出任何其他方法。
至于按别名分组,似乎取决于别名内公式的复杂程度。如果别名没有引用任何实际的列,或者已经被分组的列,那么一切正常,但是未包含在分组中的列上的别名会引发错误。
我似乎记得在我大学时代的某个地方读到或听到过,从视图中选择比从一堆连接的表中选择要快,但我不知道这是不是真的。
使用视图的最后一个优势:Excel 中的数据透视表。我认为没有加入表格的方法,或者至少在向导界面中没有。在 Microsoft Query 中进行连接可能是可能的,但我还没有尝试过,因为我现在才想到这个想法。
I used to use them all the time, now rarely. However, I do all my data access thru stored procedures so the usefulness of a view is somewhat less since the SP can hide the complexity of the join where needed.
I'd still consider using a view if a had a particularly complicated joined of many tables, from which I needed to then build many SP's on top of, but to be honest, I can't think of any I have in production right now.
The other scenario would I would use one would be where my users have access to the database for generating their own reports, and I wanted to hide the underlying complexity for them.
视图比复杂查询更容易测试。当您想对 SQL 进行单元测试时,视图就是帮助。