SELECT A, B FROM TABLE_1 WHERE A IN (SELECT A FROM TABLE_2)If TABLE_1 has index on A then it won't be used by outer query. Problem is caused by missed subquery optimization in MySQL 5.x, outer query won't use indexes if subquery is used:
- http://bugs.mysql.com/bug.php?id=9021
- http://bugs.mysql.com/bug.php?id=18826
- http://bugs.mysql.com/bug.php?id=9090
Thus there are two ways to fix indices issue:
1. use JOIN instead of subselect where it's possible, i.e.
SELECT A, B FROM TABLE_1 t1 INNER JOIN TABLE_2 t2 ON t1.A=t2.A2. use EXISTS for subqueries, i.e.
SELECT A, B FROM TABLE_1 t1 WHERE EXISTS (SELECT 1 FROM TABLE_2 t2 WHERE t1.A=t2.A)
In both approaches we force to use index on A from TABLE_1. These described features are really performed tweaks and they work well in production for us.
Article from MySQL Reference Manual about IN subqueries optimization
Problems with subqueries are fixed only in 6.0


0 коммент.:
Post a Comment