mysql where過濾條件中and連接的兩個條件的順序不必和建立的聯合索引的字段順序一致


aa表

mysql> select * from aa;
+------+--------+--------+
| id   | name   | other  |
+------+--------+--------+
|    1 | asdf   | dfdfd  |
|    2 | sdf    | fdfd   |
|    3 | dfasdf | dfdasd |
|    4 | fasdf  | fdasd  |
|    5 | asdf   | dasd   |
|    6 | bsdf   | hell0  |
+------+--------+--------+

聯合索引

mysql> show index from aa;
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table | Non_unique | Key_name    | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| aa    |          1 | aa_id_name  |            1 | id          | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |
| aa    |          1 | aa_id_name  |            2 | name        | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+

執行計划

mysql> explain select * from aa where id = 5 and name = 'asdf';
+----+-------------+-------+------+------------------------+------------+---------+-------------+------+-------------+
| id | select_type | table | type | possible_keys          | key        | key_len | ref         | rows | Extra       |
+----+-------------+-------+------+------------------------+------------+---------+-------------+------+-------------+
|  1 | SIMPLE      | aa    | ref  | aa_id_name,idx_id_name | aa_id_name | 24      | const,const |    1 | Using where |
+----+-------------+-------+------+------------------------+------------+---------+-------------+------+-------------+
1 row in set (0.02 sec)

mysql> explain select * from aa where name = 'asdf' and id = 5;
+----+-------------+-------+------+------------------------+------------+---------+-------------+------+-------------+
| id | select_type | table | type | possible_keys          | key        | key_len | ref         | rows | Extra       |
+----+-------------+-------+------+------------------------+------------+---------+-------------+------+-------------+
|  1 | SIMPLE      | aa    | ref  | aa_id_name,idx_id_name | aa_id_name | 24      | const,const |    1 | Using where |
+----+-------------+-------+------+------------------------+------------+---------+-------------+------+-------------+
1 row in set (0.00 sec)

總結:不管where過濾條件中id在前還是name在前都是用了聯合索引


免責聲明!

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



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