如何让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 |
+----+--------------------+-------+------+---------------+------+---------+------+----------+-------------+
答案 0 :(得分:4)
如果您执行inner join
,您将获得所需的结果。
自:
select * from t1 where uid in (select id from t0);
要:
select * from t1 join t0 on t1.t0id = t0.id
答案 1 :(得分: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)