mysql 在联合查询中解释
对查询执行 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”。 这种行为的原因是什么? 谢谢
After performing EXPLAIN on a query:
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%'
composed by the UNION of 4 tables I get this:
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)
When each component of the union is explained, the types are "INDEX" however, union result's type is "ALL".
Which is the reason for this behavior?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 UNION ALL 而不是 UNION - 否则 MySQL 将尝试删除任何重复的行(可能会减去表的不确定性,因为它正在查看结果集)。
另外,您是否对 UNION 的结果有 ORDER BY 或 WHERE 子句? 同样,这将在结果集上执行,而不是在表级别上执行。
Try using UNION ALL instead of UNION - otherwise MySQL will try to remove any duplicate rows (presumably minus the table indecies, as it's looking at the result set).
Also, do you have an ORDER BY or WHERE clause on the result of the UNION? Again, this will be performed on the result set, rather than at the table level.