3

如何让 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 回答 2

4

如果你执行一个inner join,你会得到你想要的结果。

从:

select * from t1 where uid in (select id from t0);

至:

select * from t1 join t0 on t1.t0id = t0.id

http://en.wikipedia.org/wiki/Join_(SQL)#Inner_join

于 2013-04-20T14:19:45.827 回答
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)
于 2013-04-20T14:19:53.947 回答