(2).const
表最多有一个匹配行,它将在查询开始时被读取。因为仅有一行,在这行的列值可被优化器剩余部分认为是常数。const表很快,因为它们只读取一次!
const用于用常数值比较PRIMARY KEY或UNIQUE索引的所有部分时。在下面的查询中,tbl_name可以用于const表:
select * from tbl_name where primary_key=1; select * from tbl_name where primary_key_part1=1和 primary_key_part2=2; |
例如:
mysql> explain select * from t3 where id=3952602; +----+-------------+-------+-------+-------------------+---------+---------+-------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+-------------------+---------+---------+-------+------+-------+ | 1 | SIMPLE | t3 | const | PRIMARY,idx_t3_id | PRIMARY | 4 | const | 1 | | +----+-------------+-------+-------+-------------------+---------+---------+-------+------+-------+ |
(3). eq_ref
对于每个来自于前面的表的行组合,从该表中读取一行。这可能是最好的联接类型,除了const类型。它用在一个索引的所有部分被联接使用并且索引是UNIQUE或PRIMARY KEY。
eq_ref可以用于使用= 操作符比较的带索引的列。比较值可以为常量或一个使用在该表前面所读取的表的列的表达式。
在下面的例子中,MySQL可以使用eq_ref联接来处理ref_tables:
select * FROM ref_table,other_table where ref_table.key_column=other_table.column; select * FROM ref_table,other_table where ref_table.key_column_part1=other_table.column AND ref_table.key_column_part2=1; |
例如
mysql> create unique index idx_t3_id on t3(id) ; Query OK, 1000 rows affected (0.03 sec) Records: 1000 Duplicates: 0 Warnings: 0 mysql> explain select * from t3,t4 where t3.id=t4.accountid; +----+-------------+-------+--------+-------------------+-----------+---------+----------------------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+-------------------+-----------+---------+----------------------+------+-------+ | 1 | SIMPLE | t4 | ALL | NULL | NULL | NULL | NULL | 1000 | | | 1 | SIMPLE | t3 | eq_ref | PRIMARY,idx_t3_id | idx_t3_id | 4 | dbatest.t4.accountid | 1 | | +----+-------------+-------+--------+-------------------+-----------+---------+----------------------+------+-------+ |
(4).ref
对于每个来自于前面的表的行组合,所有有匹配索引值的行将从这张表中读取。如果联接只使用键的最左边的前缀,或如果键不是UNIQUE或PRIMARY KEY(换句话说,如果联接不能基于关键字选择单个行的话),则使用ref。如果使用的键仅仅匹配少量行,该联接类型是不错的。
ref可以用于使用=或<=>操作符的带索引的列。
在下面的例子中,MySQL可以使用ref联接来处理ref_tables:
select * FROM ref_table where key_column=expr; select * FROM ref_table,other_table where ref_table.key_column=other_table.column; select * FROM ref_table,other_table where ref_table.key_column_part1=other_table.column AND ref_table.key_column_part2=1; |