2013-04-20 99 views
2

如何让MySQL首先运行子查询并且只运行一次? MySQL现在为表t1中的每一行运行内部查询,这是性能灾难。如何首先运行子查询并且只运行一次

explain select * from t1 where uid in (select id from t0); 
+----+--------------------+-------+------+---------------+------+---------+------+----------+-------------+ 
| id | select_type  | table | type | possible_keys | key | key_len | ref | rows  | Extra  | 
+----+--------------------+-------+------+---------------+------+---------+------+----------+-------------+ 
| 1 | PRIMARY   | t1 | ALL | NULL   | NULL | NULL | NULL | 18954249 | Using where | 
| 2 | DEPENDENT SUBQUERY | t0 | ALL | NULL   | NULL | NULL | NULL | 12749 | Using where | 
+----+--------------------+-------+------+---------------+------+---------+------+----------+-------------+ 

回答

4

以下2将工作速度比你目前的query,哪一个能更好地伸缩取决于你的数据库结构

SELECT 
    * 
FROM 
    t1 t 
    JOIN t0 ON (t.uid = t0.id)  << If there are 2 row matches on table `t0`, it shall return duplicated rows (t1 table contents duplicated, you could use a distinct to avoid such cases) OR use the second query instead 

SELECT 
    * 
FROM 
    t1 t 
    WHERE EXISTS (select 1 from t0 WHERE t0.id = t.uid) 
+3

是MySQL的*仍然*无法正确地优化子查询?这令人失望。 – XTF 2013-04-20 14:20:39

+0

是的,这里有关于优化这种查询的更多信息http://dev.mysql.com/doc/refman/5.1/en/subquery-optimization-with-exists.html – Akash 2013-04-20 14:22:49