Home > Database > Mysql Tutorial > body text

How Can I Get MySQL to Use Indices for View Queries?

Barbara Streisand
Release: 2024-11-12 01:19:02
Original
692 people have browsed it

How Can I Get MySQL to Use Indices for View Queries?

Getting MySQL to Utilize an Index for View Queries

Query: How do I encourage MySQL to leverage an index for a view query?

Answer: While using views in MySQL may not be ideal, MySQL can utilize indices for view queries when provided with appropriate index structures.

Detailed Explanation:

MySQL's view queries are distinct from other databases because the optimizer does not "push" predicates from the outer query into the view query. In this case, the outer query filters on happened_in, but MySQL does not apply this filter when executing the view query.

As a result, the view query is processed separately, creating a temporary table (a derived table). When the outer query runs, it uses the derived table as a row source, evaluating the happened_in = 2006 predicate then.

To improve performance, a covering index can be defined:

CREATE INDEX highscores_IX3 ON highscores (player, happened_in, score)
Copy after login

This index includes all columns referenced in the view query, with player as the leading column (equality predicate) followed by happened_in (GROUP BY). Including score makes the index a covering index, allowing MySQL to retrieve all necessary data from the index alone.

Alternatively, consider using a standalone query that does not utilize a derived table, which can provide better performance in some cases:

SELECT player, MAX(score) AS highest_score, happened_in
FROM highscores
WHERE player = 24 AND happened_in = 2006
GROUP BY player, happened_in
Copy after login

With this modification and an appropriate covering index, MySQL should be able to optimize the view query, significantly improving performance by leveraging the available indices.

The above is the detailed content of How Can I Get MySQL to Use Indices for View Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template