开发者

Is using views for everything a crazy idea?

I'm working on building a MySQL database and I'm thinking that rather than encode a bunch of complex join queries in the front end I'll create a view for any queries I need and then have all the front end code do simple SELECT whatever FROM some_view WHERE something=5; queries.

It seems like a grea开发者_如何学Pythont idea as it abstracts away the underlying schema so the front end doesn't need to know about it and given that MySQL can merge views into queries I'd think this would be no less efficient than the more direct solution.

Now for the question: Is this a stupid idea for some reason I'm not spotting?


Note: This would only go two layers deep, e.i. views would only reference tables, never views.


Views can simplify the amount of text you need to create a query, but layering views on top of one another is a bad practice.

That encapsulation also risks poor performing queries, because the views need to be executed before being able to join to one another--all that logic inside might not apply to what you need for the ultimate result, so being lazy can easily mean a query that doesn't perform as well as it should.

Because the views are queries that are only run when called, you won't know about missing references until runtime.

Be aware that when using SELECT * in a view, the database captures the column list when the CREATE VIEW statement was run - if the columns change, you need to refresh the view to pick up the changes.

There's also no performance difference between a view and running the query the view is based on. With the exception of materialized views (which MySQL doesn't support), views are just a prepared statement. If simple enough, WHERE predicates can be pushed from the FROM view WHERE .... into the inner query, but it means no use of functions and isn't reliable.

Conclusion

OK, but be careful.


Provided that you don't nest your views I am of the opinion that it's a good idea to code data access this way. (Remember than MS has said for years that CRUD should be done via sp's)

Not everybody agrees with me, but I like the abstraction of the data model in this way... thinking of DB calls as methods. Though I tend to do it using stored procedures, it simplifies data model changes and keeps query optimizations transparent to the app consuming the data.

Personally, I think it forces app developers to treat SQL as declarative (as it is intended) because you remove their ability to treat it otherwise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜