1. 官方文档:http://dev.mysql.com/doc/refman/5.5/en/create-table.html
-
KEYis normally a synonym forINDEX. The key attributePRIMARY KEYcan also be specified as justKEYwhen given in a column definition. This was implemented for compatibility with other database systems. -
A
UNIQUEindex 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, aUNIQUEindex permits multipleNULLvalues for columns that can containNULL. -
A
PRIMARY KEYis 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 KEYis alwaysPRIMARY, which thus cannot be used as the name for any other kind of index.If you do not have a
PRIMARY KEYand an application asks for thePRIMARY KEYin your tables, MySQL returns the firstUNIQUEindex that has noNULLcolumns as thePRIMARY KEY.In
InnoDBtables, keep thePRIMARY KEYshort 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, “InnoDBTable and Index Structures”.) -
In the created table, a
PRIMARY KEYis placed first, followed by allUNIQUEindexes, and then the nonunique indexes. This helps the MySQL optimizer to prioritize which index to use and also more quickly to detect duplicatedUNIQUEkeys. -
A
PRIMARY KEYcan be a multiple-column index. However, you cannot create a multiple-column index using thePRIMARY KEYkey 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 KEYorUNIQUEindex consists of only one column that has an integer type, you can also refer to the column as_rowidinSELECTstatements. -
In MySQL, the name of a
PRIMARY KEYisPRIMARY. 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_nameSHOW INDEXSyntax”.
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。
本文详细解释了MySQL中主键与索引的区别、作用及创建方式,包括如何选择合适的主键,以及如何利用索引来优化查询效率。
3740

被折叠的 条评论
为什么被折叠?



