问题
I have 2 tables:
t_cities
(idCity
,idCountry
,name
,population
)t_countries
(idCountry
,name
)
t_cities
has 50000 rows so I create a VIEW with the cities from UK (only 1100):
CREATE VIEW v_city_uk AS SELECT * FROM t_cities WHERE idCountry = 140
Everything is fine so far, I get a VIEW with 1100 rows.
The query
SELECT COUNT(*) FROM v_city_uk
returns 1100, but the EXPLAIN:
EXPLAIN SELECT COUNT(*) FROM v_city_uk
says that it is checking the 50000 rows to execute this query. Why?
Is there any way to make this not happen? Because I create the view to speed up the queries not to be the same.
EDIT: An "aggregate table" is what I need, Thanks to matthewdavidson.
回答1:
Because a view is not a precompiled query or a stored result, it is a predefined query. It executes the SELECT statements in the view, every time. Otherwise, a view would never get updated. A view is a representation of a query. It's a convenient shorthand for the programmer, but not for the machine.
In other words, when you
SELECT something FROM YourView
And YourView is defined by
CREATE VIEW YourView AS SELECT stuff FROM sometable
INNER JOIN othertable ON sometable.column = othertable.column
what's actually being run is
SELECT something FROM
(SELECT stuff FROM sometable
INNER JOIN othertable ON sometable.column = othertable.column)
If you want to store a result, you should use an aggregate table.
来源:https://stackoverflow.com/questions/10908064/mysql-explain-select-from-a-view-is-looking-in-all-rows-of-the-main-table