2013-04-20 50 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