2

对查询执行 EXPLAIN 后:

explain 
select name from t1 where name like '%smthing%'
UNION ALL
select name from t2 where name like '%smthing%'
UNION ALL
select name from t3 where name like '%smthing%'
UNION ALL
select name from t4 where name like '%smthing%'

由 4 个表的 UNION 组成,我得到这个:

 id  select_type   table         type    possible_keys  key     key_len  ref         rows  Extra                   
 1  PRIMARY       t1             index   (NULL)         name    152      (NULL)      337  Using where; Using index
 2  UNION         t2             index   (NULL)         name    152      (NULL)    3842  Using where; Using index
 3  UNION         t3             index   (NULL)         name    452      (NULL)     204  Using where; Using index
 4  UNION         t4             index   (NULL)         name    452      (NULL)    8269  Using where; Using index
(NULL)  UNION RESULT  <union1,2,3,4>  ALL     (NULL)         (NULL)  (NULL)   (NULL)  (NULL)  

当解释联合的每个组件时,类型是“INDEX”但是联合结果的类型是“ALL”。这种行为的原因是什么?谢谢

4

1 回答 1

3

尝试使用 UNION ALL 而不是 UNION - 否则 MySQL 将尝试删除任何重复的行(大概减去表的索引,因为它正在查看结果集)。

此外,您是否对 UNION 的结果有 ORDER BY 或 WHERE 子句?同样,这将在结果集上执行,而不是在表级别。

于 2009-04-27T12:49:01.577 回答