您需要显式地创建索引,还是在定义主键时隐式创建索引?MyISAM和InnoDB的答案一样吗?


当前回答

我想这就是答案

mysql> create table test(id int primary key, s varchar(20));
Query OK, 0 rows affected (0.06 sec)

mysql> show indexes from test \G
*************************** 1. row ***************************
        Table: test
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: id
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null:
   Index_type: BTREE
      Comment:
Index_comment:
1 row in set (0.00 sec)

其他回答

主键总是被索引。对于MyISAM和InnoDB也是如此,对于所有支持索引的存储引擎也是如此。

MyISAM和InnoDB的主键都隐式索引。可以通过对使用主键的查询使用EXPLAIN来验证这一点。

我想这就是答案

mysql> create table test(id int primary key, s varchar(20));
Query OK, 0 rows affected (0.06 sec)

mysql> show indexes from test \G
*************************** 1. row ***************************
        Table: test
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: id
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null:
   Index_type: BTREE
      Comment:
Index_comment:
1 row in set (0.00 sec)

你不必显式地为主键创建索引…这是默认的。

根据http://dev.mysql.com/doc/refman/5.0/en/constraint-primary-key.html的说法,这似乎是隐含的