简体   繁体   中英

mysql Views vs Stored Procedure

I'm currently designing my mysql db for an app i'm developing.

I like it when Stored Procedures are short and readable, and since my db involved some join statements, I thought maybe I should create Views with all the joins and query these Views from my Stored Procedures .

At first it sounds great, but when I though about performance, I realised that whenever a Stored Procedure is called it will run at least 2 queries:

  1. The View query
  2. The Stored Procedure query on that View

while using the join statements inside the Stored Procedure I will have only on query doing the joining and the selection from the join.

Am I right?

If so - what will be a good practice to maintain great development performance in terms of elegant code writing ?

"great development performance" and "elegant code" are two worlds apart. You should not be pairing them so closely.

You are correct in saying that the creation of views beforehand will add a layer of inefficiency. If you are worried more about performance, then I would just put your joined queries directly in your stored procedure. Querying from a view will force the view to repopulate, which is one additional query you don't need.

That being said, one additional query probably won't make or break your database performance.

If you are really concerned about you code tidiness, I would suggest considering what data you are actually using from your join statements to see if you can shorten them or break them down. For example, are you using multiple columns or rows of data? Or are you just querying for a single value? If the latter, consider creating a function that returns this value. This will also help separate your code out of your stored procedure.

A DBMS does not typically do separate queries in the situtation you are describing. It textually expands an appearance of a view name where used in a query and evaluates the entire resulting new expression. It does not evaluate a separate query for the view. Use a stored procedure to group and/or parameterize operations other than what a view gives you (namely parameterization by bases/views only and one select only).

That being said, you may not be able to sufficiently optimize a query that contains a view name compared to a query you could get by expanding the view definition and rearranging. But that is true whether or not the query in question is in a stored procedure.

See MySQL documentation . (Note a user comment that says that certain view clauses only prevent inlining/merging when they are in the outermost select expression.) Or this dba.stackexchange.com google 'mysql view optimization' hit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM