MySQL不支援子查詢最佳化一例

來源:互聯網
上載者:User

MySQL不支援子查詢最佳化一例

一建立表

create table tt1(id int primary key, c1 INT);
create table tt2(id int primary key, c2 INT);
insert into tt1 values(1,1),(2,2),(3,3),(4,4);
insert into tt2 values(1,2),(2,2);

二 執行計畫與問題

mysql> explain EXTENDED SELECT tt1.c1, (SELECT tt2.c2 FROM tt2 WHERE c2=10) FROM tt1, tt2;
+----+-------------+-------+-------+---------------+---------+---------+------+------+----------+---------------------------------------+
| id | select_type | table | type  | possible_keys | key    | key_len | ref  | rows | filtered | Extra                                |
+----+-------------+-------+-------+---------------+---------+---------+------+------+----------+---------------------------------------+
|  1 | PRIMARY    | tt2  | index | NULL          | PRIMARY | 4      | NULL |    2 |  100.00 | Using index                          |
|  1 | PRIMARY    | tt1  | ALL  | NULL          | NULL    | NULL    | NULL |    4 |  100.00 | Using join buffer (Block Nested Loop) |
|  2 | SUBQUERY    | tt2  | ALL  | NULL          | NULL    | NULL    | NULL |    2 |  100.00 | Using where                          |
+----+-------------+-------+-------+---------------+---------+---------+------+------+----------+---------------------------------------+
3 rows in set, 1 warning (0.00 sec)
這個語句的執行順序是怎麼執行的,就是按照執行計畫這樣從上到下執行嗎?

三 分析

---id值為1的兩個,是From子句中的tt1和tt2,用塊嵌套迴圈串連演算法做內串連,tt2是外表,所以先啟動的是tt2;後啟動的是tt1。
---id值為2的是目標列中的子查詢,後於FROM子句中的表執行。發生在串連後要求目標列的值發給用戶端階段。
---理論上是可以最佳化的,方法為:目標列只有一列和WHERE條件相同,所以,可以推知此子查詢的結果是2。
---但是,MySQL沒有最佳化這樣的子查詢。
---另外,對於這裡的子查詢,如果其結果返回多行,則MySQL會報告錯誤:ERROR 1242 (21000): Subquery returns more than 1 row。

--------------------------------------分割線 --------------------------------------

Ubuntu 14.04下安裝MySQL

《MySQL權威指南(原書第2版)》清晰中文掃描版 PDF

Ubuntu 14.04 LTS 安裝 LNMP Nginx\PHP5 (PHP-FPM)\MySQL

Ubuntu 14.04下搭建MySQL主從伺服器

Ubuntu 12.04 LTS 構建高可用分布式 MySQL 叢集

Ubuntu 12.04下原始碼安裝MySQL5.6以及Python-MySQLdb

MySQL-5.5.38通用二進位安裝

--------------------------------------分割線 --------------------------------------

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.