利用主键优化查询
? ? ? ? ?聽別人說mysql可以利用主鍵優化查詢,我們今天來嘗試一下,先創建2個表。
包含主鍵的表t1:
mysql> create table t1(-> id int unsigned auto_increment primary key,-> name varchar(20)-> ); Query OK, 0 rows affected (0.09 sec)不包含主鍵的表t2:
mysql> create table t2(-> name varchar(20) not null,-> score varchar(20)); Query OK, 0 rows affected (0.04 sec)現在執行一下查詢語句:
mysql> explain select * from t1 where id=3; +----+-------------+-------+-------+---------------+---------+---------+-------+ ------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref |rows | Extra | +----+-------------+-------+-------+---------------+---------+---------+-------+ ------+-------+ | 1 | SIMPLE | t1 | const | PRIMARY | PRIMARY | 4 | const |1 | | +----+-------------+-------+-------+---------------+---------+---------+-------+ ------+-------+ 1 row in set (0.00 sec)有主鍵的其查找對應的type為const。
mysql> explain select * from t2 where name=45; +----+-------------+-------+------+---------------+------+---------+------+----- -+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows| Extra | +----+-------------+-------+------+---------------+------+---------+------+----- -+-------------+ | 1 | SIMPLE | t2 | ALL | NULL | NULL | NULL | NULL | 3| Using where | +----+-------------+-------+------+---------------+------+---------+------+----- -+-------------+ 1 row in set (0.01 sec)沒有主鍵的其查找對應的type為ALL,ALL是全盤掃描,屬于效率最低的一種。
效率:const > All,可見主鍵可以優化查詢。
總結