CREATE TABLE `mvc_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`realname` varchar(20) NOT NULL,
`email` varchar(254) NOT NULL,
`face` varchar(100) NOT NULL,
`url` varchar(200) NOT NULL,
`about` longtext NOT NULL,
`addtime` datetime(6) NOT NULL,
`area_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `mvc_user_area_id_0ee8c234_fk_mvc_area_id` (`area_id`),
CONSTRAINT `mvc_user_area_id_0ee8c234_fk_mvc_area_id` FOREIGN KEY (`area_id`) REFERENCES `mvc_area` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
解释 PRIMARY KEY, KEY, CONSTRAINT:
1. 这里的PRIMARY KEY (`id`), 说明 字段 id是这个表的主键,主键的隐性说明就是唯一(unique)且不能为空(Not null),一个表只能有一个主键,当然主键可以包含一个或多个字段, 当然一个表也可以不设置 主键
2. KEY, 这里的key等同于index,所以这里也可以用 index,就是索引,这是为了和其他类型的数据库系统兼容, “KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.”
{INDEX|KEY} [index_name] [index_type] (index_col_name,...) [index_option] ...
KEY `mvc_user_area_id_0ee8c234_fk_mvc_area_id` (`area_id`), mvc_user_area_id_0ee8c234_fk_mvc_area_id 就是 index_name, area_id就是index_col_name, 也就是说在colume area_id上建立索引,index_type可以不指定
如果关键字属性PRIMARY KEY在列定义中指定,则PRIMARY KEY也可以只写为KEY, 比如:
`id` int(11) NOT NULL AUTO_INCREMENT KEY, 等同于 `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY
比如:
CREATE TABLE `mvc_user22` (
`id` int(11) NOT NULL AUTO_INCREMENT KEY,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`realname` varchar(20) NOT NULL,
`email` varchar(254) NOT NULL,
`face` varchar(100) NOT NULL,
`url` varchar(200) NOT NULL,
`about` longtext NOT NULL,
`addtime` datetime(6) NOT NULL,
`area_id` int(11) NOT NULL,
KEY `mvc_user_area_id_0ee8c234_fk_mvc_area_id` (`area_id`),
CONSTRAINT `mvc_user22_area_id_0ee8c234_fk_mvc_area_id` FOREIGN KEY (`area_id`) REFERENCES `mvc_area` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
3. CONSTRAINT `mvc_user_area_id_0ee8c234_fk_mvc_area_id` FOREIGN KEY (`area_id`) REFERENCES `mvc_area` (`id`), 指定一个 约束, 这里是一个外键约束, 这个外键是 表 mvc_area的主键 id, 所以插入数据的时候,会检查是否表mvc_area有这个id值,如果没有,则插入会出错。
注意: 同一数据库中不同表的约束(CONSTRAINT )不能重名?,不然创建表的时候会出错,会提示:
Can\'t write; duplicate key in table \'mvc_user22\'
索引(index|key)可以重名。
根据官方文档:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,...) [table_options] [partition_options]
create_definition: col_name column_definition | [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) [index_option] ... | {INDEX|KEY} [index_name] [index_type] (index_col_name,...) [index_option] ... | [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...) [index_option] ... | {FULLTEXT|SPATIAL} [INDEX|KEY] [index_name] (index_col_name,...) [index_option] ... | [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) reference_definition | CHECK (expr)
index_col_name: col_name [(length)] [ASC | DESC] index_type: USING {BTREE | HASH} index_option: KEY_BLOCK_SIZE [=] value | index_type | WITH PARSER parser_name | COMMENT \'string\' reference_definition: REFERENCES tbl_name (index_col_name,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option] reference_option: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT
Indexes and Foreign Keys
-
CONSTRAINTsymbolIf the
CONSTRAINTclause is given, thesymbolsymbolvalue, if used, must be unique in the database. A duplicatesymbolresults in an error. If the clause is not given, or asymbolis not included following theCONSTRAINTkeyword, a name for the constraint is created automatically. -
PRIMARY KEYA unique index where all key columns must be defined as
NOT 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. (See Section 14.8.2.1, “Clustered and Secondary Indexes”.)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 KEYconsists 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.22, “SHOW INDEX Syntax”.tbl_name -
KEY | INDEXKEYis 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. -
UNIQUEA
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. If you specify a prefix value for a column in aUNIQUEindex, the column values must be unique within the prefix.If a
UNIQUEindex consists of only one column that has an integer type, you can also refer to the column as_rowidinSELECTstatements. -
FULLTEXTA
FULLTEXTindex is a special type of index used for full-text searches. Only theInnoDBandMyISAMstorage engines supportFULLTEXTindexes. They can be created only fromCHAR,VARCHAR, andTEXTcolumns. Indexing always happens over the entire column; column prefix indexing is not supported and any prefix length is ignored if specified. See Section 12.9, “Full-Text Search Functions”, for details of operation. AWITH PARSERclause can be specified as anindex_optionvalue to associate a parser plugin with the index if full-text indexing and searching operations need special handling. This clause is valid only forFULLTEXTindexes. BothInnoDBandMyISAMsupport full-text parser plugins. See Full-Text Parser Plugins and Section 28.2.4.4, “Writing Full-Text Parser Plugins” for more information. -
SPATIALYou can create
SPATIALindexes on spatial data types. Spatial types are supported only forMyISAMandInnoDBtables, and indexed columns must be declared asNOT NULL. See Section 11.5, “Spatial Data Types”. -
FOREIGN KEYMySQL supports foreign keys, which let you cross-reference related data across tables, and foreign key constraints, which help keep this spread-out data consistent. For definition and option information, see
reference_definition, andreference_option.Partitioned tables employing the
InnoDBstorage engine do not support foreign keys. See Section 22.6, “Restrictions and Limitations on Partitioning”, for more information. -
CHECKThe
CHECKclause is parsed but ignored by all storage engines. See Section 1.8.2.3, “Foreign Key Differences”. -
index_col_name-
An
index_col_namespecification can end withASCorDESC. These keywords are permitted for future extensions for specifying ascending or descending index value storage. Currently, they are parsed but ignored; index values are always stored in ascending order. -
Prefixes, defined by the
lengthattribute, can be up to 767 bytes long forInnoDBtables or 3072 bytes if theinnodb_large_prefixoption is enabled. For MyISAM tables, the prefix limit is 1000 bytes.Prefix limits are measured in bytes, whereas the prefix length in
CREATE TABLE,ALTER TABLE, andCREATE INDEXstatements is interpreted as number of characters for nonbinary string types (CHAR,VARCHAR,TEXT) and number of bytes for binary string types (BINARY,VARBINARY,BLOB). Take this into account when specifying a prefix length for a nonbinary string column that uses a multibyte character set.
-
-
index_typeSome storage engines permit you to specify an index type when creating an index. The syntax for the
index_typespecifier isUSING.type_nameExample:
CREATE TABLE lookup (id INT, INDEX USING BTREE (id)) ENGINE = MEMORY;The preferred position for
USINGis after the index column list. It can be given before the column list, but support for use of the option in that position is deprecated and will be removed in a future MySQL release. -
index_optionindex_optionvalues specify additional options for an index.-
KEY_BLOCK_SIZEFor
MyISAMtables,KEY_BLOCK_SIZEoptionally specifies the size in bytes to use for index key blocks. The value is treated as a hint; a different size could be used if necessary. AKEY_BLOCK_SIZEvalue specified for an individual index definition overrides the table-levelKEY_BLOCK_SIZEvalue.For information about the table-level
KEY_BLOCK_SIZEattribute, see Table Options. -
WITH PARSERThe
WITH PARSERoption can only be used withFULLTEXTindexes. It associates a parser plugin with the index if full-text indexing and searching operations need special handling. BothInnoDBandMyISAMsupport full-text parser plugins. If you have aMyISAMtable with an associated full-text parser plugin, you can convert the table toInnoDBusingALTER TABLE. -
COMMENTIn MySQL 5.7, index definitions can include an optional comment of up to 1024 characters.
You can set the
InnoDBMERGE_THRESHOLDvalue for an individual index using theindex_optionCOMMENTclause. SeeSection 14.6.13, “Configuring the Merge Threshold for Index Pages”.
For more information about permissible
index_optionvalues, see Section 13.1.14, “CREATE INDEX Syntax”. For more information about indexes, see Section 8.3.1, “How MySQL Uses Indexes”. -
-
For
reference_definitionsyntax details and examples, see Section 13.1.18.6, “Using FOREIGN KEY Constraints”. For information specific to foreign keys inInnoDB, see Section 14.8.1.6, “InnoDB and FOREIGN KEY Constraints”.InnoDBandNDBtables support checking of foreign key constraints. The columns of the referenced table must always be explicitly named. BothON DELETEandON UPDATEactions on foreign keys are supported. For more detailed information and examples, see Section 13.1.18.6, “Using FOREIGN KEY Constraints”. For information specific to foreign keys inInnoDB, see Section 14.8.1.6, “InnoDB and FOREIGN KEY Constraints”.For other storage engines, MySQL Server parses and ignores the
FOREIGN KEYandREFERENCESsyntax inCREATE TABLEstatements. See Section 1.8.2.3, “Foreign Key Differences”.ImportantFor users familiar with the ANSI/ISO SQL Standard, please note that no storage engine, including
InnoDB, recognizes or enforces theMATCHclause used in referential integrity constraint definitions. Use of an explicitMATCHclause will not have the specified effect, and also causesON DELETEandON UPDATEclauses to be ignored. For these reasons, specifyingMATCHshould be avoided.The
MATCHclause in the SQL standard controls howNULLvalues in a composite (multiple-column) foreign key are handled when comparing to a primary key.InnoDBessentially implements the semantics defined byMATCH SIMPLE, which permit a foreign key to be all or partiallyNULL. In that case, the (child table) row containing such a foreign key is permitted to be inserted, and does not match any row in the referenced (parent) table. It is possible to implement other semantics using triggers.Additionally, MySQL requires that the referenced columns be indexed for performance. However,
InnoDBdoes not enforce any requirement that the referenced columns be declaredUNIQUEorNOT NULL. The handling of foreign key references to nonunique keys or keys that containNULLvalues is not well defined for operations such asUPDATEorDELETE CASCADE. You are advised to use foreign keys that reference only keys that are bothUNIQUE(orPRIMARY) andNOT NULL.MySQL parses but ignores “inline
REFERENCESspecifications” (as defined in the SQL standard) where the references are defined as part of the column specification. MySQL acceptsREFERENCESclauses only when specified as part of a separateFOREIGN KEYspecification. -
For information about the
RESTRICT,CASCADE,SET NULL,NO ACTION, andSET DEFAULToptions, see Section 13.1.18.6, “Using FOREIGN KEY Constraints”.