I need to perform the following query, which is very slow:
select subject, count(*) AS Number from (select DISTINCT userid,subject from my_test) AS FILTERED GROUP BY subject ORDER BY Number DESC;
However, the following two queries are very,very fast:
select DISTINCT userid,subject from my_test;
and
select subject, count(*) AS Number from my_test AS FILTERED GROUP BY subject ORDER BY Number DESC;
What is the problem with my inner select query? How I make it faster?
Speaking about queries - providing EXPLAIN would be helpful.
I guess both of fast queries are indexed, while if you use SELECT in FROM clause you get result set back which does not have any indexes. Also MySQL will normally materialize such subselects in temporary table which also may add significant overhead.
Generally I would avoid subselects in FROM clause unless really needed.