1. 官方文檔:http://dev.mysql.com/doc/refman/5.5/en/create-table.html
-
KEY
is normally a synonym forINDEX
. The key attributePRIMARY KEY
can also be specified as justKEY
when given in a column definition. This was implemented for compatibility with other database systems. -
A
UNIQUE
index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, aUNIQUE
index permits multipleNULL
values for columns that can containNULL
. -
A
PRIMARY KEY
is a unique index where all key columns must be defined asNOT NULL
. If they are not explicitly declared asNOT NULL
, MySQL declares them so implicitly (and silently). A table can have only onePRIMARY KEY
. The name of aPRIMARY KEY
is alwaysPRIMARY
, which thus cannot be used as the name for any other kind of index.If you do not have a
PRIMARY KEY
and an application asks for thePRIMARY KEY
in your tables, MySQL returns the firstUNIQUE
index that has noNULL
columns as thePRIMARY KEY
.In
InnoDB
tables, keep thePRIMARY KEY
short to minimize storage overhead for secondary indexes. Each secondary index entry contains a copy of the primary key columns for the corresponding row. (SeeSection 14.3.11, “InnoDB
Table and Index Structures”.) -
In the created table, a
PRIMARY KEY
is placed first, followed by allUNIQUE
indexes, and then the nonunique indexes. This helps the MySQL optimizer to prioritize which index to use and also more quickly to detect duplicatedUNIQUE
keys. -
A
PRIMARY KEY
can be a multiple-column index. However, you cannot create a multiple-column index using thePRIMARY KEY
key attribute in a column specification. Doing so only marks that single column as primary. You must use a separatePRIMARY KEY(
clause.index_col_name
, ...) -
If a
PRIMARY KEY
orUNIQUE
index consists of only one column that has an integer type, you can also refer to the column as_rowid
inSELECT
statements. -
In MySQL, the name of a
PRIMARY KEY
isPRIMARY
. For other indexes, if you do not assign a name, the index is assigned the same name as the first indexed column, with an optional suffix (_2
,_3
,...
) to make it unique. You can see index names for a table usingSHOW INDEX FROM
. See Section 13.7.5.23, “tbl_name
SHOW INDEX
Syntax”.
Note that "primary" is called PRIMARY KEY not INDEX.
KEY is something on the logical level, describes your table and database design (i.e. enforces referential integrity
...)
INDEX is something on the physical level, helps improve access time for table operations.
Behind every PK there is (usually) unique index created (automatically).
3. http://wenku.baidu.com/view/ff96febb1a37f111f1855bf8.html
在創建innoDB表時,在每張表中都只能有一個主鍵,如果在創建表時沒有明確地定義主鍵(Primary Key),則innoDB引擎會自動按照如下方式選擇或創建主鍵:首先看錶中是否有非空唯一索引(Unique NOT NULL)如果有,則該列即爲主鍵。 不符合上述條件,則自動創建一個6字節大小的RowID。