Mysql 如何先运行子查询,并且只运行一次

Mysql 如何先运行子查询,并且只运行一次,mysql,Mysql,如何让MySQL先运行子查询,并且只运行一次?现在MySQL为表t1中的每一行运行内部查询,这是一个性能灾难 explain select * from t1 where uid in (select id from t0); +----+--------------------+-------+------+---------------+------+---------+------+----------+-------------+ | id | select_type |

如何让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 |
+----+--------------------+-------+------+---------------+------+---------+------+----------+-------------+

如果执行
内部联接
,您将获得所需的结果

发件人:

致:


下面的2个将比当前的
查询运行得更快,哪一个扩展得更好取决于您的数据库结构

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

MySQL是否仍然无法正确优化子查询?这令人失望。是的,这里有更多关于优化此类查询的信息
select * from t1 join t0 on t1.t0id = t0.id
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)