I have a table and a query that looks below. For a working example, see This SQL Fiddle .
SELECT o.property_B, SUM(o.score1), w.score FROM o INNER JOIN ( SELECT o.property_B, SUM(o.score2) AS score FROM o GROUP BY property_B ) w ON w.property_B = o.property_B WHERE o.property_A = 'specific_A' GROUP BY property_B;
With my real data, this query takes 27 seconds. However, if I first create w as a temporary table and the index_B property, all together takes ~ 1 second.
CREATE TEMPORARY TABLE w AS SELECT o.property_B, SUM(o.score2) AS score FROM o GROUP BY property_B; ALTER TABLE w ADD INDEX `property_B_idx` (property_B); SELECT o.property_B, SUM(o.score1), w.score FROM o INNER JOIN w ON w.property_B = o.property_B WHERE o.property_A = 'specific_A' GROUP BY property_B; DROP TABLE IF EXISTS w;
Is there a way to combine the best of these two queries? That is, one query with the benefits of indexing speed in a subquery?
EDIT
After Mehran answers below, I read this explanation in the MySQL documentation :
Starting with MySQL 5.6.3, the optimizer more efficiently processes subqueries in the FROM clause (i.e., derived tables):
...
In cases where a subquery in the FROM clause requires materialization, the optimizer can speed up access to the result by adding an index to the materialized table. If such an index allows access to the table, it can significantly reduce the amount of data that must be read during query execution. Consider the following query:
SELECT * FROM t1 JOIN (SELECT * FROM t2) AS derived_t2 ON t1.f1=derived_t2.f1;
The optimizer builds the index over column f1 from the derived_t2, if this allows the use of ref access for the execution plan with the lowest cost. After adding an index, the optimizer can process the materialized view in the same way as a regular table with an index, and it also benefits from the generated index. The overhead of creating an index is negligible compared to the cost of executing a query without an index. If access for access results in a higher cost than any other access method, no index is created and the optimizer loses nothing.