mysql create table
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
-
CONSTRAINT
symbol
If the
CONSTRAINT
clause is given, thesymbol
symbol
value, if used, must be unique in the database. A duplicatesymbol
results in an error. If the clause is not given, or asymbol
is not included following theCONSTRAINT
keyword, a name for the constraint is created automatically. -
PRIMARY KEY
A 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 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. (See Section 14.8.2.1, “Clustered and Secondary Indexes”.)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
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.22, “SHOW INDEX Syntax”.tbl_name
-
KEY | INDEX
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. -
UNIQUE
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
. If you specify a prefix value for a column in aUNIQUE
index, the column values must be unique within the prefix.If a
UNIQUE
index consists of only one column that has an integer type, you can also refer to the column as_rowid
inSELECT
statements. -
FULLTEXT
A
FULLTEXT
index is a special type of index used for full-text searches. Only theInnoDB
andMyISAM
storage engines supportFULLTEXT
indexes. They can be created only fromCHAR
,VARCHAR
, andTEXT
columns. 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 PARSER
clause can be specified as anindex_option
value to associate a parser plugin with the index if full-text indexing and searching operations need special handling. This clause is valid only forFULLTEXT
indexes. BothInnoDB
andMyISAM
support full-text parser plugins. See Full-Text Parser Plugins and Section 28.2.4.4, “Writing Full-Text Parser Plugins” for more information. -
SPATIAL
You can create
SPATIAL
indexes on spatial data types. Spatial types are supported only forMyISAM
andInnoDB
tables, and indexed columns must be declared asNOT NULL
. See Section 11.5, “Spatial Data Types”. -
FOREIGN KEY
MySQL 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
InnoDB
storage engine do not support foreign keys. See Section 22.6, “Restrictions and Limitations on Partitioning”, for more information. -
CHECK
The
CHECK
clause is parsed but ignored by all storage engines. See Section 1.8.2.3, “Foreign Key Differences”. -
index_col_name
-
An
index_col_name
specification can end withASC
orDESC
. 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
length
attribute, can be up to 767 bytes long forInnoDB
tables or 3072 bytes if theinnodb_large_prefix
option 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 INDEX
statements 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_type
Some storage engines permit you to specify an index type when creating an index. The syntax for the
index_type
specifier isUSING
.type_name
Example:
CREATE TABLE lookup (id INT, INDEX USING BTREE (id)) ENGINE = MEMORY;
The preferred position for
USING
is 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_option
index_option
values specify additional options for an index.-
KEY_BLOCK_SIZE
For
MyISAM
tables,KEY_BLOCK_SIZE
optionally 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_SIZE
value specified for an individual index definition overrides the table-levelKEY_BLOCK_SIZE
value.For information about the table-level
KEY_BLOCK_SIZE
attribute, see Table Options. -
WITH PARSER
The
WITH PARSER
option can only be used withFULLTEXT
indexes. It associates a parser plugin with the index if full-text indexing and searching operations need special handling. BothInnoDB
andMyISAM
support full-text parser plugins. If you have aMyISAM
table with an associated full-text parser plugin, you can convert the table toInnoDB
usingALTER TABLE
. -
COMMENT
In MySQL 5.7, index definitions can include an optional comment of up to 1024 characters.
You can set the
InnoDB
MERGE_THRESHOLD
value for an individual index using theindex_option
COMMENT
clause. SeeSection 14.6.13, “Configuring the Merge Threshold for Index Pages”.
For more information about permissible
index_option
values, see Section 13.1.14, “CREATE INDEX Syntax”. For more information about indexes, see Section 8.3.1, “How MySQL Uses Indexes”. -
-
For
reference_definition
syntax 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”.InnoDB
andNDB
tables support checking of foreign key constraints. The columns of the referenced table must always be explicitly named. BothON DELETE
andON UPDATE
actions 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 KEY
andREFERENCES
syntax inCREATE TABLE
statements. 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 theMATCH
clause used in referential integrity constraint definitions. Use of an explicitMATCH
clause will not have the specified effect, and also causesON DELETE
andON UPDATE
clauses to be ignored. For these reasons, specifyingMATCH
should be avoided.The
MATCH
clause in the SQL standard controls howNULL
values in a composite (multiple-column) foreign key are handled when comparing to a primary key.InnoDB
essentially 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,
InnoDB
does not enforce any requirement that the referenced columns be declaredUNIQUE
orNOT NULL
. The handling of foreign key references to nonunique keys or keys that containNULL
values is not well defined for operations such asUPDATE
orDELETE CASCADE
. You are advised to use foreign keys that reference only keys that are bothUNIQUE
(orPRIMARY
) andNOT NULL
.MySQL parses but ignores “inline
REFERENCES
specifications” (as defined in the SQL standard) where the references are defined as part of the column specification. MySQL acceptsREFERENCES
clauses only when specified as part of a separateFOREIGN KEY
specification. -
For information about the
RESTRICT
,CASCADE
,SET NULL
,NO ACTION
, andSET DEFAULT
options, see Section 13.1.18.6, “Using FOREIGN KEY Constraints”.