Mysql - “EXPLAIN SELECT” from a VIEW is looking in all rows of the main table

梦想与她 提交于 2019-12-13 19:17:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!