mysql中explain輸出列之id的用法詳解


參考mysql5.7 en manual,對列id的解釋:

The SELECT identifier. This is the sequential number of the SELECT within the query. The value can be NULL if the row refers to the union result of other rows. In this case, the table column shows a value like <unionM,N> to indicate that the row refers to the union of the rows with id values of M and N.

翻譯:SELECT標識符,它是查詢里的SELECT的順序編號,如果這行涉及其他行聯合的結果,這個值可能是NULL。在這種情況下,explain輸出列中的table列會展示一個像<unionM,N>的值來指出該行涉及帶id值為M和N的行的聯合。

示例
# 快速創建三個表tb1, tb2, tb3
# 創建tb1
mysql> create table tb1(
    -> id int unsigned not null primary key auto_increment comment '主鍵,自增',
    -> name varchar(30) not null default '' comment '姓名'
    -> ) engine=innodb auto_increment=1 default charset=utf8 collate=utf8_general_ci;
Query OK, 0 rows affected (0.01 sec)

# 創建tb2
mysql> create table tb2 like tb1;
Query OK, 0 rows affected (0.02 sec)

# 創建tb3
mysql> create table tb3 like tb1;
Query OK, 0 rows affected (0.02 sec)

一,id相同,按table列由上至下順序執行

# id都是1,值相同,執行順序是從上至下依次是tb1, tb2, tb3
mysql> explain select tb2.* from tb1, tb2, tb3 where tb1.id=tb2.id and tb1.id=tb3.id and tb1.name='jerry';

二,id不同,如果是子查詢,id的序號會遞增,id的值越大優先級越高,越先被執行

# 分別向三個表中插入記錄
mysql> insert into tb1 values(null, 'tom');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tb2 select * from tb1;
Query OK, 1 row affected (0.01 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into tb3 select * from tb1;
Query OK, 1 row affected (0.01 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from tb1, tb2, tb3;
+----+------+----+------+----+------+
| id | name | id | name | id | name |
+----+------+----+------+----+------+
|  1 | tom  |  1 | tom  |  1 | tom  |
+----+------+----+------+----+------+
1 row in set (0.00 sec)

# id不相同並且子查詢的id是遞增的,此時table列的執行順序是tb3, tb1, tb2
# tb3的id是3優先被執行,其次是tb1, tb2
mysql> explain select tb2.* from tb2 where id=(select id from tb1 where id=(select tb3.id from tb3 where tb3.name='tom'));

三,id相同不同,同時存在

# id相同都是1,順序執行依次是tb3, tb2
mysql> explain select tb2.* from (select tb3.id from tb3 where tb3.name='') as n1, tb2 where n1.id=tb2.id;

在上面的例子中沒有模擬出id相同不同混合的情況,可以看下下面的截圖

如上圖所示,id如果相同,可以認為是一組,(本組內)從上往下順序執行;在所有組中,id值越大,優先級越高,越先執行。

四,對於使用union的情況

# id有相同也有不同,相同id為一組,所以執行順序為tb1, tb2, tb3
mysql> explain select tb3.* from tb3 union select tb2.* from (select tb1.* from tb1) as n1, tb2;

總結

注意:以上示例顯示的結果是在centos7和mysql5.7.26上測試所得,其他mysql版本或環境結果可能會有所不同。

歡迎訪問我的個人站點:瑾年筆記


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM