mysql 视图优势,在MySQL中使用视图的优势

I've learned that views can be used to create custom "table views" (so to say) that aggregate related data from multiple tables.

My question is: what are the advantages of views? Specifically, let's say I have two tables:

event | eid, typeid, name

eventtype | typeid, max_team_members

Now I create a view:

eventdetails | event.eid, event.name, eventtype.max_team_members

| where event.typeid=eventtype.typeid

Now if I want to maximum number of members allowed in a team for some event, I could:

use the view

do a join query (or maybe a stored procedure).

What would be my advantages/disadvantages in each method?

Another query: if data in table events and eventtypes gets updated, is there any overhead involved in updating the data in the view (considering it caches resultant data)?

解决方案

A view is not stored separately: when you query a view, the view is replaced with the definition of that view. So and changes to the data in the tables will show up immediately via the view.

In addition to the security feature pointed out earlier:

If you're writing a large number of queries that would perform that join, it factors out that SQL code. Like doing some operations in a function used in several places, it can make your code easier to read/write/debug.

It would also allow you to change how the join is performed in the future in one place. Perhaps a 1-to-many relationship could become a many-to-many relationship, introducing an extra table in the join. Or you may decide to denormalize and include all of the eventtype fields in each event record so that you don't have to join each time (trading space for query execution time).

You could further split tables later, changing it to a 3-way join, and other queries using the view wouldn't have to be rewritten.

You could add new columns to the table(s) and change the view to leave out the new columns so that some older queries using "select *" don't break when you change the table definitions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值