在 MySQL 中应用 VIEW 有哪些好的例子?
我读过MySQL
的CREATE VIEW
语法,但从未在实践中使用过它。
请给我展示一些它的应用示例。
I have read about the CREATE VIEW
syntax of MySQL
, but never used it in practice.
Please show me some examples of its applications.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无论使用哪种 RDBMS,视图都用于简化或限制对基础表的访问。
一个例子是更改列的名称,使最终用户更容易理解和使用它们,并对联接进行非规范化。
另一个是防止访问敏感信息(例如工资单):从表中删除所有权限并通过视图提供受控访问。
Regardless of the RDBMS, a View is used to simplify or restrict access to underlying tables.
One example is changing the names of columns to make them easier to uderstand and consume by end users, and denormalising joins.
Another is preventing access to sensitive information (such as payroll): all permissions are removed from tables and controlled access provided through views.
非物化视图实际上是一个宏 - 引用视图意味着它包含的查询在视图引用位置使用。 IE:
这个:
...将返回一个与您使用以下内容相匹配的结果集:
我提到了非物化视图,但 MySQL 不支持物化视图。其他数据库(Oracle、SQL Server 称之为“索引视图”、DB2)支持物化视图,但这不是问题所在。以后我写视图的时候只讲非物化视图。
视图用于封装/抽象 - 除非用户具有访问权限,否则他们无法看到视图的底层查询是什么。这取决于具体情况是好还是坏 - 如果您担心提供数据模型信息,则很好;在大多数其他情况下都不好。在视图中使用 ORDER BY 是不好的,因为它需要资源来应用订单,而由于封装/抽象,其他人可能会应用 order by - 这是资源的浪费。分层视图(基于视图构建的视图)也是另一种不好的做法 - 在视图运行之前您不会收到错误。
视图过去用于提供对数据的访问,而无需授予对表的访问权限,但它们已经发展到支持更新基础表。在这种情况下,我更愿意授予对表的访问权限。
A non-materialized view is effectively a macro - referencing a view means the query it contains is used in the view references place. IE:
This:
...will return a resultset that matches what you'd get from using:
I mentioned non-materialized, but MySQL doesn't support materialized views. Other databases (Oracle, SQL Server calls them "indexed views", DB2) support materialized views, but that's not the question. From now on, I'll only talk about non-materialized views when I write about views.
Views are used for encapsulation/abstraction - unless the user has access, they can't see what the underlying query for a view is. This is good/bad depending on the situation - good if you're worried about giving out data model information; bad in most other cases. Using an ORDER BY in a view is bad because it takes resources to apply the order, which because of encapsulation/abstraction someone else might apply an order by to -- it's a waste of resources. Layering views (views built on views) is also another bad practice - you won't get an error until the view is run.
Views used to provide access to data without needing to grant access to the table, but they've evolved to support updating the underlying table. I prefer to grant access to the table for such situations.