You should always use EXPLAIN
to determine how your query will work.
Unfortunately, MySQL will execute your subquery as DEPENDENT QUERY, which means that the subquery will be executed for each row in the outer query. You think MySQL will be smart enough to find that the subquery is not a correlated subquery and will only run it once, alas, it is not yet so smart.
So, MySQL scans all rows in students, runs a subquery for each row, and does not use any indexes in an external query.
Writing a query as a JOIN will allow MySQL to use indexes, and the following query will be the best way to write it:
SELECT COUNT(*) AS count FROMstudents s JOIN classes c ON c.id = s.classes_id AND c.departments_id = 1 WHERE s.status = 1
This would use the following indexes:
students(`status`) classes(`id`, `departements_id`) : multi-column index
source share