1

I am creating a booking application and have normalised the database as much as is possible. My question is the following, should I create Views in the database that combine the tables again before I do selective selects on the combined view in the WHERE clause or is it better to filter the tables with selects before joining them in a view?

EDIT: Included example.

The first scenario creates the combined view first, and then performs the SELECT on the combined view (this view may have thousands of records):

CREATE VIEW appc as 
SELECT * FROM appointment
LEFT OUTER JOIN chair
ON appointment.chair_idchair = chair.idchair

SELECT * FROM appc
WHERE chair_idchair = 1;

The second scenario will first filter the table in the left of the join and then create a view based on the filtered table, then the join will be made using this much smaller view:

CREATE VIEW appf as 
SELECT * FROM appointment
WHERE chair_idchair = 1;

SELECT * FROM appf
LEFT OUTER JOIN chair
ON appf.chair_idchair = chair.idchair
4

2 回答 2

1

As a general rule, the optimizer is pretty smart, and can see right through the views when constructing a query plan. If you try to "help" the optimizer by pre-selecting some data, you may be hiding information from the optimizer that would have allowed it to create a smarter, more-optimal plan.

于 2013-07-03T17:51:16.027 回答
1

It makes little difference to MySQL. MySQL (unlike some other RDBMS brands) does not store anything in the view itself. Think of a MySQL view more like a macro. In most cases, querying the view is exactly like executing the query you defined as the view.

Applying subsequent conditions in the WHERE clause when querying the view is combined pretty transparently with the view's query, as if you had written the full query and given it one more condition.

Exception: you can optionally create the view with ALGORITHM=TEMPTABLE, to force it to store the results of the view in a temp table, and then apply extra conditions you specified in your query. In this case, it would be better to build the conditions into the view's query, to reduce the size of the resulting temp table.

See http://dev.mysql.com/doc/refman/5.6/en/view-algorithms.html for more details.

于 2013-07-03T18:11:14.830 回答