- 15.1.20.1 由 CREATE TABLE15.1.20.1 Files Created by CREATE TABLE
- 15.1.20.2 创建临时表 Statement15.1.20.2 CREATE TEMPORARY TABLE Statement
- 15.1.20.3 创建 TABLE ...LIKE Statement15.1.20.3 CREATE TABLE ... LIKE Statement
- 15.1.20.4 创建 TABLE ...SELECT 语句 Statement15.1.20.4 CREATE TABLE ... SELECT Statement
- 15.1.20.5 外键约束<15.1.20.5 FOREIGN KEY Constraints
- 15.1.20.6 CHECK 约束15.1.20.6 CHECK Constraints
- 15.1.20.7 静默列规范变更15.1.20.7 Silent Column Specification Changes
- 15.1.20.8 创建表和生成列15.1.20.8 CREATE TABLE and Generated Columns
- 15.1.20.9 次级索引和生成列<15.1.20.9 Secondary Indexes and Generated Columns
- 15.1.20.10 隐形列15.1.20.10 Invisible Columns
- 15.1.20.11 生成的隐形主键15.1.20.11 Generated Invisible Primary Keys
- 15.1.20.12 设置 NDB 注释选项15.1.20.12 Setting NDB Comment Options
CREATE [TEMPORARY] TABLE [IF NOT EXISTS]tbl_name(create_definition,...) [table_options] [partition_options] CREATE [TEMPORARY] TABLE [IF NOT EXISTS]tbl_name[(create_definition,...)] [table_options] [partition_options] [IGNORE | REPLACE] [AS]query_expressionCREATE [TEMPORARY] TABLE [IF NOT EXISTS]tbl_name{ LIKEold_tbl_name| (LIKEold_tbl_name) }create_definition: {col_namecolumn_definition| {INDEX | KEY} [index_name] [index_type] (key_part,...) [index_option] ... | {FULLTEXT | SPATIAL} [INDEX | KEY] [index_name] (key_part,...) [index_option] ... | [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (key_part,...) [index_option] ... | [CONSTRAINT [symbol]] UNIQUE [INDEX | KEY] [index_name] [index_type] (key_part,...) [index_option] ... | [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (col_name,...)reference_definition|check_constraint_definition}column_definition: {data_type[NOT NULL | NULL] [DEFAULT {literal| (expr)} ] [VISIBLE | INVISIBLE] [AUTO_INCREMENT] [UNIQUE [KEY]] [[PRIMARY] KEY] [COMMENT 'string'] [COLLATEcollation_name] [COLUMN_FORMAT {FIXED | DYNAMIC | DEFAULT}] [ENGINE_ATTRIBUTE [=] 'string'] [SECONDARY_ENGINE_ATTRIBUTE [=] 'string'] [STORAGE {DISK | MEMORY}] [reference_definition] [check_constraint_definition] |data_type[COLLATEcollation_name] [GENERATED ALWAYS] AS (expr) [VIRTUAL | STORED] [NOT NULL | NULL] [VISIBLE | INVISIBLE] [UNIQUE [KEY]] [[PRIMARY] KEY] [COMMENT 'string'] [reference_definition] [check_constraint_definition] }data_type: (see Chapter 13, Data Types)key_part: {col_name[(length)] | (expr)} [ASC | DESC]index_type: USING {BTREE | HASH}index_option: { KEY_BLOCK_SIZE [=]value|index_type| WITH PARSERparser_name| COMMENT 'string' | {VISIBLE | INVISIBLE} |ENGINE_ATTRIBUTE[=] 'string' |SECONDARY_ENGINE_ATTRIBUTE[=] 'string' }check_constraint_definition: [CONSTRAINT [symbol]] CHECK (expr) [[NOT] ENFORCED]reference_definition: REFERENCEStbl_name(key_part,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETEreference_option] [ON UPDATEreference_option]reference_option: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULTtable_options:table_option[[,]table_option] ...table_option: { AUTOEXTEND_SIZE [=]value| AUTO_INCREMENT [=]value| AVG_ROW_LENGTH [=]value| [DEFAULT] CHARACTER SET [=]charset_name| CHECKSUM [=] {0 | 1} | [DEFAULT] COLLATE [=]collation_name| COMMENT [=] 'string' | COMPRESSION [=] {'ZLIB' | 'LZ4' | 'NONE'} | CONNECTION [=] 'connect_string' | {DATA | INDEX} DIRECTORY [=] 'absolute path to directory' | DELAY_KEY_WRITE [=] {0 | 1} | ENCRYPTION [=] {'Y' | 'N'} | ENGINE [=]engine_name| ENGINE_ATTRIBUTE [=] 'string' | INSERT_METHOD [=] { NO | FIRST | LAST } | KEY_BLOCK_SIZE [=]value| MAX_ROWS [=]value| MIN_ROWS [=]value| PACK_KEYS [=] {0 | 1 | DEFAULT} | PASSWORD [=] 'string' | ROW_FORMAT [=] {DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT} | START TRANSACTION | SECONDARY_ENGINE_ATTRIBUTE [=] 'string' | STATS_AUTO_RECALC [=] {DEFAULT | 0 | 1} | STATS_PERSISTENT [=] {DEFAULT | 0 | 1} | STATS_SAMPLE_PAGES [=]value|tablespace_option| UNION [=] (tbl_name[,tbl_name]...) }partition_options: PARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY [ALGORITHM={1 | 2}] (column_list) | RANGE{(expr) | COLUMNS(column_list)} | LIST{(expr) | COLUMNS(column_list)} } [PARTITIONSnum] [SUBPARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY [ALGORITHM={1 | 2}] (column_list) } [SUBPARTITIONSnum] ] [(partition_definition[,partition_definition] ...)]partition_definition: PARTITIONpartition_name[VALUES {LESS THAN {(expr|value_list) | MAXVALUE} | IN (value_list)}] [[STORAGE] ENGINE [=]engine_name] [COMMENT [=] 'string' ] [DATA DIRECTORY [=] ''] [INDEX DIRECTORY [=] 'data_dir'] [MAX_ROWS [=]index_dirmax_number_of_rows] [MIN_ROWS [=]min_number_of_rows] [TABLESPACE [=] tablespace_name] [(subpartition_definition[,subpartition_definition] ...)]subpartition_definition: SUBPARTITIONlogical_name[[STORAGE] ENGINE [=]engine_name] [COMMENT [=] 'string' ] [DATA DIRECTORY [=] ''] [INDEX DIRECTORY [=] 'data_dir'] [MAX_ROWS [=]index_dirmax_number_of_rows] [MIN_ROWS [=]min_number_of_rows] [TABLESPACE [=] tablespace_name]tablespace_option: TABLESPACEtablespace_name[STORAGE DISK] | [TABLESPACEtablespace_name] STORAGE MEMORYquery_expression:SELECT ... (Some valid select or union statement)
CREATE TABLE一个带有名字的表。你必须为该表拥有 CREATE 权限。CREATE TABLE creates a table with
the given name. You must have the
CREATE privilege for the table.
默认情况下,表是在默认数据库中创建,使用 InnoDB 存储引擎。如果表存在、没有默认数据库,或数据库不存在,就会发生错误。By default, tables are created in the default database, using the
InnoDB storage engine. An error
occurs if the table exists, if there is no default database, or if
the database does not exist.
MySQL 对表的数量没有限制。底层文件系统可能对表示表的文件数量有限制。各个存储引擎可能会施加特定于引擎的约束。 InnoDB 允许最多 40 亿个表。MySQL has no limit on the number of tables. The underlying file
system may have a limit on the number of files that represent
tables. Individual storage engines may impose engine-specific
constraints. InnoDB permits up to 4 billion
tables.
有关表的物理表示信息,请参见 第 15.1.20.1 节,“由 CREATE TABLE 创建的文件”。For information about the physical representation of a table, see Section 15.1.20.1, “Files Created by CREATE TABLE”.
CREATE
TABLE 语句,在本节的以下主题下进行了描述:There are several aspects to the CREATE
TABLE statement, described under the following topics in
this section:
表名Table Name
tbl_name可以将表名指定为
db_name.tbl_name,以在特定数据库中创建表。无论是否存在默认数据库,这都有效,前提是该数据库存在。如果使用引用标识符,请分别引用数据库和表名。例如,写作`mydb`.`mytbl`,而不是`mydb.mytbl`。The table name can be specified asdb_name.tbl_nameto create the table in a specific database. This works regardless of whether there is a default database, assuming that the database exists. If you use quoted identifiers, quote the database and table names separately. For example, write`mydb`.`mytbl`, not`mydb.mytbl`.允许的表名规则在 第 11.2 节,“模式对象名称” 中给出。Rules for permissible table names are given in Section 11.2, “Schema Object Names”.
IF NOT EXISTS如果表已存在,可防止发生错误。然而,并不会验证现有表的结构是否与
CREATE TABLE语句中指定的结构相同。Prevents an error from occurring if the table exists. However, there is no verification that the existing table has a structure identical to that indicated by theCREATE TABLEstatement.
临时表Temporary Tables
在创建表时可以使用 TEMPORARY 关键字。TEMPORARY 表仅在当前会话中可见,且会话关闭时会自动删除。欲了解更多信息,请参见 第 15.1.20.2 节,“CREATE TEMPORARY TABLE 语句”。You can use the TEMPORARY keyword when creating
a table. A TEMPORARY table is visible only
within the current session, and is dropped automatically when the
session is closed. For more information, see
Section 15.1.20.2, “CREATE TEMPORARY TABLE Statement”.
表克隆与复制Table Cloning and Copying
LIKE使用
CREATE TABLE ... LIKE基于另一个表的定义创建空表,包括原表中定义的任何列属性和索引:UseCREATE TABLE ... LIKEto create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table:CREATE TABLE
new_tblLIKEorig_tbl;欲了解更多信息,请参见 第 15.1.20.3 节,“CREATE TABLE ... LIKE 语句”。For more information, see Section 15.1.20.3, “CREATE TABLE ... LIKE Statement”.
[AS]query_expression要从另一个表创建表,可在
CREATE TABLE语句末尾添加SELECT语句:To create one table from another, add aSELECTstatement at the end of theCREATE TABLEstatement:CREATE TABLE
new_tblAS SELECT * FROMorig_tbl;欲了解更多信息,请参见 第 15.1.20.4 节,“CREATE TABLE ... SELECT 语句”。For more information, see Section 15.1.20.4, “CREATE TABLE ... SELECT Statement”.
IGNORE | REPLACEIGNORE和REPLACE选项指示在使用SELECT语句复制表时如何处理重复唯一键值的行。TheIGNOREandREPLACEoptions indicate how to handle rows that duplicate unique key values when copying a table using aSELECTstatement.欲了解更多信息,请参见 第 15.1.20.4 节,“CREATE TABLE ... SELECT 语句”。For more information, see Section 15.1.20.4, “CREATE TABLE ... SELECT Statement”.
列数据类型和属性Column Data Types and Attributes
每个表的列数有硬性上限 4096,但对于特定表的有效最大值可能更少,这取决于 第 10.4.7 节,“表列数和行大小限制” 中讨论的因素。There is a hard limit of 4096 columns per table, but the effective maximum may be less for a given table and depends on the factors discussed in Section 10.4.7, “Limits on Table Column Count and Row Size”.
data_typedata_type表示列定义中的数据类型。有关指定列数据类型的语法的完整描述以及每种类型的属性信息,请参见 第 13 章,数据类型。data_typerepresents the data type in a column definition. For a full description of the syntax available for specifying column data types, as well as information about the properties of each type, see Chapter 13, Data Types.AUTO_INCREMENT仅适用于整数类型。AUTO_INCREMENTapplies only to integer types.字符数据类型 (
CHAR,VARCHAR,TEXT类型,ENUM,SET,以及任何同义词) 可以包含CHARACTER SET来指定该列的字符集。CHARSET是CHARACTER SET的同义词。字符集的排序规则可以通过COLLATE属性来指定,同时可以指定其他属性。详情请参见 第 12 章,字符集、排序规则、Unicode。示例:Character data types (CHAR,VARCHAR, theTEXTtypes,ENUM,SET, and any synonyms) can includeCHARACTER SETto specify the character set for the column.CHARSETis a synonym forCHARACTER SET. A collation for the character set can be specified with theCOLLATEattribute, along with any other attributes. For details, see Chapter 12, Character Sets, Collations, Unicode. Example:CREATE TABLE t (c CHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin);
MySQL 8.4 在字符列定义中把长度规格解释为字符数。
BINARY和VARBINARY的长度单位为字节。MySQL 8.4 interprets length specifications in character column definitions in characters. Lengths forBINARYandVARBINARYare in bytes.表,如果没有任何可变长度列(
CHAR,VARCHAR,BINARY,以及VARBINARYcolumns, indexes can be created that use only the leading part of column values, usingsyntax to specify an index prefix length.col_name(length)BLOB以及TEXTcolumns also can be indexed, but a prefix length 必须 be given. Prefix lengths are given in characters for nonbinary string types and in bytes for binary string types. That is, index entries consist of the firstlengthcharacters of each column value forCHAR,VARCHAR,以及TEXTcolumns, and the firstlengthbytes of each column value forBINARY,VARBINARY,以及BLOBcolumns. Indexing only a prefix of column values like this can make the index file much smaller. For additional information about index prefixes, see 第 15.1.15 节,“CREATE INDEX 语句”.ForCHAR,VARCHAR,BINARY, andVARBINARYcolumns, indexes can be created that use only the leading part of column values, usingsyntax to specify an index prefix length.col_name(length)BLOBandTEXTcolumns also can be indexed, but a prefix length must be given. Prefix lengths are given in characters for nonbinary string types and in bytes for binary string types. That is, index entries consist of the firstlengthcharacters of each column value forCHAR,VARCHAR, andTEXTcolumns, and the firstlengthbytes of each column value forBINARY,VARBINARY, andBLOBcolumns. Indexing only a prefix of column values like this can make the index file much smaller. For additional information about index prefixes, see Section 15.1.15, “CREATE INDEX Statement”.只有
InnoDB和MyISAM存储引擎支持索引BLOB和TEXT列。例如:Only theInnoDBandMyISAMstorage engines support indexing onBLOBandTEXTcolumns. For example:CREATE TABLE test (blob_col BLOB, INDEX(blob_col(10)));
如果指定的索引前缀超过最大列数据类型大小,
CREATE TABLE对索引的处理如下:If a specified index prefix exceeds the maximum column data type size,CREATE TABLEhandles the index as follows:对于非唯一索引,如果启用了严格 SQL 模式,则会发生错误;如果未启用严格 SQL 模式,则索引长度会被缩减到不超过最大列数据类型的大小,并会产生警告。For a nonunique index, either an error occurs (if strict SQL mode is enabled), or the index length is reduced to lie within the maximum column data type size and a warning is produced (if strict SQL mode is not enabled).
对于唯一索引,无论 SQL 模式如何,都会发生错误,因为缩短索引长度可能会允许插入不符合指定唯一性要求的非唯一条目。For a unique index, an error occurs regardless of SQL mode because reducing the index length might enable insertion of nonunique entries that do not meet the specified uniqueness requirement.
JSON列不可索引。你可以通过在生成的列上创建一个索引,从JSON。详见 索引生成列以提供 JSON 列索引,作为详细示例。JSONcolumns cannot be indexed. You can work around this restriction by creating an index on a generated column that extracts a scalar value from theJSONcolumn. See Indexing a Generated Column to Provide a JSON Column Index, for a detailed example.
NOT NULL | NULLNOT NULL | NULL如果没有指定
NULL,也没有指定NOT NULL,那么该列将被视为NULL。If neitherNULLnorNOT NULLis specified, the column is treated as thoughNULLhad been specified.在 MySQL 8.4 中,只有
InnoDB,MyISAM以及MEMORY存储引擎支持对可以是NULL。在其他情况下,你必须将索引列声明为NOT NULL,否则会出现错误。In MySQL 8.4, only theInnoDB,MyISAM, andMEMORYstorage engines support indexes on columns that can haveNULLvalues. In other cases, you must declare indexed columns asNOT NULLor an error results.DEFAULTDEFAULT的默认值。关于默认值处理的更多信息,包括列定义中没有显式
DEFAULT值的情况,请参见 第 13.6 节,“Data type Default Values”。Specifies a default value for a column. For more information about default value handling, including the case that a column definition includes no explicitDEFAULTvalue, see Section 13.6, “Data Type Default Values”.如果
NO_ZERO_DATE或NO_ZERO_IN_DATESQL 模式启用且该模式中日期值默认不正确,CREATE TABLE如果未启用严格 SQL 模式会发出警告,启用严格模式则会报错。例如,启用NO_ZERO_IN_DATE,c1 DATE DEFAULT '2010-00-00'会发出警告。If theNO_ZERO_DATEorNO_ZERO_IN_DATESQL mode is enabled and a date-valued default is not correct according to that mode,CREATE TABLEproduces a warning if strict SQL mode is not enabled and an error if strict mode is enabled. For example, withNO_ZERO_IN_DATEenabled,c1 DATE DEFAULT '2010-00-00'produces a warning.VISIBLE,INVISIBLEVISIBLE,INVISIBLE指定列可见性。默认为
VISIBLE,如果这两个关键词都不存在。表必须至少有一个可见列。尝试让所有列都不可见会产生错误。更多信息请参见 第 15.1.20.10 节,“Invisible Columns”。Specify column visibility. The default isVISIBLEif neither keyword is present. A table must have at least one visible column. Attempting to make all columns invisible produces an error. For more information, see Section 15.1.20.10, “Invisible Columns”.AUTO_INCREMENT整数列可以具有附加属性
AUTO_INCREMENT。当你插入一个值为NULL(推荐) 或者0到一个索引AUTO_INCREMENT列时,该列被设置为下一个序列值。通常这是,其中value+1value当前表中该列的最大值。AUTO_INCREMENT序列从1.An integer column can have the additional attributeAUTO_INCREMENT. When you insert a value ofNULL(recommended) or0into an indexedAUTO_INCREMENTcolumn, the column is set to the next sequence value. Typically this is, wherevalue+1valueis the largest value for the column currently in the table.AUTO_INCREMENTsequences begin with1.插入行后要检索
AUTO_INCREMENT值,可以使用LAST_INSERT_ID()SQL 函数,或mysql_insert_id()C API 函数。参见 第 14.15 节,“信息函数”,以及 mysql_insert_id()。To retrieve anAUTO_INCREMENTvalue after inserting a row, use theLAST_INSERT_ID()SQL function or themysql_insert_id()C API function. See Section 14.15, “Information Functions”, and mysql_insert_id().如果启用了
NO_AUTO_VALUE_ON_ZEROSQL 模式,则可以在AUTO_INCREMENT列中存储0作为0,而不会生成新的序列值。参见 第 7.1.11 节,“服务器 SQL 模式”。If theNO_AUTO_VALUE_ON_ZEROSQL mode is enabled, you can store0inAUTO_INCREMENTcolumns as0without generating a new sequence value. See Section 7.1.11, “Server SQL Modes”.开始。每个表只能有一个
AUTO_INCREMENT列,它必须被索引,并且不能有一个DEFAULTvalue. AnAUTO_INCREMENTcolumn works properly only if it contains only positive values. Inserting a negative number is regarded as inserting a very large positive number. This is done to avoid precision problems when numbers “wrap” over from positive to negative and also to ensure that you do not accidentally get anAUTO_INCREMENTcolumn that contains0.There can be only oneAUTO_INCREMENTcolumn per table, it must be indexed, and it cannot have aDEFAULTvalue. AnAUTO_INCREMENTcolumn works properly only if it contains only positive values. Inserting a negative number is regarded as inserting a very large positive number. This is done to avoid precision problems when numbers “wrap” over from positive to negative and also to ensure that you do not accidentally get anAUTO_INCREMENTcolumn that contains0.对于
MyISAM表,你可以在多列键中指定一个AUTO_INCREMENT的辅助列。参见 第 5.6.9 节,“使用 AUTO_INCREMENT”。ForMyISAMtables, you can specify anAUTO_INCREMENTsecondary column in a multiple-column key. See Section 5.6.9, “Using AUTO_INCREMENT”.为了使 MySQL 与某些 ODBC 应用程序兼容,可以使用以下查询找到最后插入行的
AUTO_INCREMENT值:To make MySQL compatible with some ODBC applications, you can find theAUTO_INCREMENTvalue for the last inserted row with the following query:SELECT * FROM
tbl_nameWHEREauto_colIS NULL此方法要求
sql_auto_is_null变量未设置为 0。参见 第 7.1.8 节,“服务器系统变量”。This method requires thatsql_auto_is_nullvariable is not set to 0. See Section 7.1.8, “Server System Variables”.有关
InnoDB和AUTO_INCREMENT的信息,请参见 第 17.6.1.6 节,“InnoDB 中的 AUTO_INCREMENT 处理”。有关AUTO_INCREMENT和 MySQL 复制的信息,请参见 第 19.5.1.1 节,“复制与 AUTO_INCREMENT”。For information aboutInnoDBandAUTO_INCREMENT, see Section 17.6.1.6, “AUTO_INCREMENT Handling in InnoDB”. For information aboutAUTO_INCREMENTand MySQL Replication, see Section 19.5.1.1, “Replication and AUTO_INCREMENT”.COMMENTCOMMENT可以使用
COMMENT选项为列指定注释,最长可达 1024 个字符。该注释可以通过SHOW CREATE TABLE和SHOW FULL COLUMNS语句显示。它还会显示在信息模式COLUMNS表的COLUMN_COMMENT列中。A comment for a column can be specified with theCOMMENToption, up to 1024 characters long. The comment is displayed by theSHOW CREATE TABLEandSHOW FULL COLUMNSstatements. It is also shown in theCOLUMN_COMMENTcolumn of the Information SchemaCOLUMNStable.COLUMN_FORMATCOLUMN_FORMAT在 NDB Cluster,还可以为
NDB,使用COLUMN_FORMAT。允许的列格式包括FIXEDDYNAMIC以及DEFAULTFIXED用于指定固定宽度存储,DYNAMIC允许列为可变宽度,DEFAULT使列使用固定宽度或可变宽度存储,具体取决于列的数据类型(可能被ROW_FORMAT指定符覆盖)。In NDB Cluster, it is also possible to specify a data storage format for individual columns ofNDBtables usingCOLUMN_FORMAT. Permissible column formats areFIXED,DYNAMIC, andDEFAULT.FIXEDis used to specify fixed-width storage,DYNAMICpermits the column to be variable-width, andDEFAULTcauses the column to use fixed-width or variable-width storage as determined by the column's data type (possibly overridden by aROW_FORMATspecifier).对于
NDB表,COLUMN_FORMAT为FIXED。ForNDBtables, the default value forCOLUMN_FORMATisFIXED.在 NDB 集群中,定义为
COLUMN_FORMAT=FIXED量为 8188 字节。欲了解更多信息及可能的变通方法,请参见 第 25.2.7.5 节,“与 NDB 集群中数据库对象相关的限制”。In NDB Cluster, the maximum possible offset for a column defined withCOLUMN_FORMAT=FIXEDis 8188 bytes. For more information and possible workarounds, see Section 25.2.7.5, “Limits Associated with Database Objects in NDB Cluster”.COLUMN_FORMAT目前对使用存储引擎的表列没有影响,除了NDBMySQL 8.4 默然忽略了COLUMN_FORMAT。COLUMN_FORMATcurrently has no effect on columns of tables using storage engines other thanNDB. MySQL 8.4 silently ignoresCOLUMN_FORMAT.ENGINE_ATTRIBUTE和SECONDARY_ENGINE_ATTRIBUTE选项用于指定主存储和次级存储引擎的列属性。这些选项保留以供未来使用。ENGINE_ATTRIBUTEandSECONDARY_ENGINE_ATTRIBUTEoptions are used to specify column attributes for primary and secondary storage engines. The options are reserved for future use.分配给此选项的值是包含有效 JSON 文档的字符串字面量或空字符串('')。无效的 JSON 会被拒绝。The value assigned to this option is a string literal containing a valid JSON document or an empty string (''). Invalid JSON is rejected.
CREATE TABLE t1 (c1 INT ENGINE_ATTRIBUTE='{"key":"value"}');ENGINE_ATTRIBUTE和SECONDARY_ENGINE_ATTRIBUTE的值可以重复而不会出错。在这种情况下,将使用最后指定的值。ENGINE_ATTRIBUTEandSECONDARY_ENGINE_ATTRIBUTEvalues can be repeated without error. In this case, the last specified value is used.ENGINE_ATTRIBUTE和SECONDARY_ENGINE_ATTRIBUTE的值不会被服务器检查,也不会在更改表的存储引擎时清除。ENGINE_ATTRIBUTEandSECONDARY_ENGINE_ATTRIBUTEvalues are not checked by the server, nor are they cleared when the table's storage engine is changed.STORAGESTORAGE对于
NDB表,可以通过STORAGE中。STORAGE DISK使列存储在磁盘上,STORAGE MEMORY内存存储被使用。CREATE TABLE语句仍必须包含TABLESPACE子句:ForNDBtables, it is possible to specify whether the column is stored on disk or in memory by using aSTORAGEclause.STORAGE DISKcauses the column to be stored on disk, andSTORAGE MEMORYcauses in-memory storage to be used. TheCREATE TABLEstatement used must still include aTABLESPACEclause:mysql>
CREATE TABLE t1 (->c1 INT STORAGE DISK,->c2 INT STORAGE MEMORY->) ENGINE NDB;ERROR 1005 (HY000): Can't create table 'c.t1' (errno: 140) mysql>CREATE TABLE t1 (->c1 INT STORAGE DISK,->c2 INT STORAGE MEMORY->) TABLESPACE ts_1 ENGINE NDB;Query OK, 0 rows affected (1.06 sec)For
NDB表,STORAGE DEFAULT等价于STORAGE MEMORY。ForNDBtables,STORAGE DEFAULTis equivalent toSTORAGE MEMORY.STORAGE子句对使用存储引擎的表无影响,除了NDB。STORAGE关键字仅在构建 mysqld;在其他版本的 MySQL 中无法识别该 mod,任何尝试使用STORAGE关键字都会引起语法错误。TheSTORAGEclause has no effect on tables using storage engines other thanNDB. TheSTORAGEkeyword is supported only in the build of mysqld that is supplied with NDB Cluster; it is not recognized in any other version of MySQL, where any attempt to use theSTORAGEkeyword causes a syntax error.GENERATED ALWAYSGENERATED ALWAYS用于指定生成的列表达式。关于 generated columns 的信息,请参见 第 15.1.20.8 节,“创建 TABLE 和生成列”。Used to specify a generated column expression. For information about generated columns, see Section 15.1.20.8, “CREATE TABLE and Generated Columns”.
存储的生成列可以被索引。
InnoDB支持在 virtual generated columns.参见 第 15.1.20.9 节,”次级索引和生成列“。Stored generated columns can be indexed.InnoDBsupports secondary indexes on virtual generated columns. See Section 15.1.20.9, “Secondary Indexes and Generated Columns”.
索引、外键和 CHECK 约束Indexes, Foreign Keys, and CHECK Constraints
索引、外键和CHECK。除了以下描述外,一般背景可参见 第 15.1.15 节,“CREATE INDEX Statement”,第 15.1.20.5 节,“FOREIGN KEY Constraints”,以及 第 15.1.20.6 节,“CHECK 约束”。Several keywords apply to creation of indexes, foreign keys, and
CHECK constraints. For general background in
addition to the following descriptions, see
Section 15.1.15, “CREATE INDEX Statement”,
Section 15.1.20.5, “FOREIGN KEY Constraints”, and
Section 15.1.20.6, “CHECK Constraints”.
CONSTRAINT symbolCONSTRAINTsymbolCONSTRAINT symbol子句可用于命名约束。如果未给出该子句,或在symbol会自动生成约束名称,但下文提到的例外。symbol值(如果使用),必须在每个模式(数据库)和约束类型中唯一。重复的symbol会导致错误。另见关于生成约束标识符长度限制的讨论,见第 11.2.1 节,“标识符长度限制”。TheCONSTRAINTclause may be given to name a constraint. If the clause is not given, or asymbolsymbolis not included following theCONSTRAINTkeyword, MySQL automatically generates a constraint name, with the exception noted below. Thesymbolvalue, if used, must be unique per schema (database), per constraint type. A duplicatesymbolresults in an error. See also the discussion about length limits of generated constraint identifiers at Section 11.2.1, “Identifier Length Limits”.Note如果
CONSTRAINT symbolclause 未在外键定义中给出,或symbol会自动生成约束名称。If theCONSTRAINTclause is not given in a foreign key definition, or asymbolsymbolis not included following theCONSTRAINTkeyword, MySQL automatically generates a constraint name.SQL 标准规定,所有类型的约束(主键、唯一索引、外键、检查)属于同一个命名空间。在 MySQL 中,每种约束类型在每个模式下都有自己的命名空间。因此,每种类型的约束名称在每个模式下必须唯一,但不同类型的约束可以有相同的名称。The SQL standard specifies that all types of constraints (primary key, unique index, foreign key, check) belong to the same namespace. In MySQL, each constraint type has its own namespace per schema. Consequently, names for each type of constraint must be unique per schema, but constraints of different types can have the same name.
PRIMARY KEYPRIMARY KEY唯一索引,所有键列必须定义为
NOT NULL如果未明确声明为NOT NULL会隐式(且无声地)声明。一个表只能有一个PRIMARY KEY。PRIMARY KEY始终是PRIMARY因此不能用作任何其他类型的索引名称。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.如果你没有
PRIMARY KEY,且应用程序在表中要求PRIMARY KEY会返回第一个UNIQUE索引,且没有NULL列,作为PRIMARY KEY。If you do not have aPRIMARY KEYand an application asks for thePRIMARY KEYin your tables, MySQL returns the firstUNIQUEindex that has noNULLcolumns as thePRIMARY KEY.在
InnoDB表中,保持PRIMARY KEY简短,以减少次级索引的存储开销。每个次级索引条目包含对应行的主键列副本。(参见 第 17.6.2.1 节,“聚类和次级索引”)InInnoDBtables, 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 17.6.2.1, “Clustered and Secondary Indexes”.)在创建的表格中,
PRIMARY KEY放在首位,然后是所有UNIQUE索引,最后是非唯一索引。这有助于 MySQL 优化器优先选择使用哪个索引,并更快地检测重复的UNIQUE密钥。In the created table, aPRIMARY 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.PRIMARY KEY可以是多列索引。然而,你不能在列规范中使用PRIMARY KEYkey 属性来创建多列索引。这样做只会将该单列标记为主列。你必须使用单独的PRIMARY KEY(key_part, ...)子句。APRIMARY 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.key_part, ...)如果一个表的
PRIMARY KEYUNIQUE NOT NULL索引,且仅由一个整数类型的列组成,你可以使用_rowid来指代索引列SELECT语句,如 Unique Indexes。If a table has aPRIMARY KEYorUNIQUE NOT NULLindex that consists of a single column that has an integer type, you can use_rowidto refer to the indexed column inSELECTstatements, as described in Unique Indexes.在 MySQL 中,
PRIMARY KEY是PRIMARY。对于其他索引,如果你不分配名称,索引将与第一个索引列相同,并可选择添加后缀(_2,_3,...)以实现唯一。你可以使用SHOW INDEX FROM tbl_name。参见 第 15.7.7.23 节,“SHOW INDEX Statement”。In MySQL, the name of aPRIMARY 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 15.7.7.23, “SHOW INDEX Statement”.tbl_nameKEY | INDEXKEY | INDEXKEY通常是INDEX。密钥属性PRIMARY KEY,也可以在列定义中指定为KEY。这是为了与其他数据库系统的兼容性而实现的。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.UNIQUEUNIQUEUNIQUE索引创建了一个约束,使得索引中的所有值必须不同。如果你尝试添加一个键值与现有行匹配的新行,就会发生错误。对于所有引擎来说,UNIQUE索引允许对可包含NULLAUNIQUEindex 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 length.如果一个表的
PRIMARY KEYUNIQUE NOT NULL索引,且仅由一个整数类型的列组成,你可以使用_rowid来指代索引列SELECT语句,如 Unique Indexes。If a table has aPRIMARY KEYorUNIQUE NOT NULLindex that consists of a single column that has an integer type, you can use_rowidto refer to the indexed column inSELECTstatements, as described in Unique Indexes.FULLTEXTFULLTEXTA
FULLTEXTindex is a special type of index used for full-text searches. Only theInnoDB以及MyISAMstorage engines supportFULLTEXTindexes. They can be created only fromCHAR,VARCHAR,以及TEXTcolumns. Indexing always happens over the entire column; column prefix indexing is not supported and any prefix length is ignored if specified. See Section 14.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 forFULLTEXT索引的表。InnoDB以及MyISAMsupport full-text parser plugins. See Full-Text Parser Plugins以及Writing Full-Text Parser Plugins for more information.AFULLTEXTindex 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 14.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.InnoDBandMyISAMsupport full-text parser plugins. See Full-Text Parser Plugins and Writing Full-Text Parser Plugins for more information.SPATIALSPATIAL你可以创建
SPATIAL索引,用于空间数据类型。空间类型仅支持InnoDB和MyISAM表,索引列必须声明为NOT NULL参见 第 13.4 节,“空间数据类型”。You can createSPATIALindexes on spatial data types. Spatial types are supported only forInnoDBandMyISAMtables, and indexed columns must be declared asNOT NULL. See Section 13.4, “Spatial Data Types”.FOREIGN KEYFOREIGN 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,以及reference_option.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, seereference_definition, andreference_option.采用
InnoDB不支持外键。更多信息请参见 第 26.6 节,“分区的限制与限制”。Partitioned tables employing theInnoDBstorage engine do not support foreign keys. See Section 26.6, “Restrictions and Limitations on Partitioning”, for more information.CHECKCHECKCHECK子句允许在表行中检查约束的创建。参见 第 15.1.20.6 节,“CHECK Constraints”。TheCHECKclause enables the creation of constraints to be checked for data values in table rows. See Section 15.1.20.6, “CHECK Constraints”.key_partA
key_partspecification can end withASC或者DESCto specify whether index values are stored in ascending or descending order. The default is ascending if no order specifier is given.Akey_partspecification can end withASCorDESCto specify whether index values are stored in ascending or descending order. The default is ascending if no order specifier is given.Prefixes, defined by the
lengthattribute, can be up to 767 bytes long forInnoDBtables that use theREDUNDANT或者COMPACTrow format. The prefix length limit is 3072 bytes forInnoDBtables that use theDYNAMIC或者COMPRESSEDrow format. ForMyISAMtables, the prefix length limit is 1000 bytes.Prefixes, defined by thelengthattribute, can be up to 767 bytes long forInnoDBtables that use theREDUNDANTorCOMPACTrow format. The prefix length limit is 3072 bytes forInnoDBtables that use theDYNAMICorCOMPRESSEDrow format. ForMyISAMtables, the prefix length limit is 1000 bytes.前缀 限制以字节为单位。然而,索引规范前缀 lengths 用于
CREATE TABLE“,ALTER TABLE”,CREATE INDEX语句被解释为非二元字符串类型的字符数(CHARVARCHAR,TEXT以及二进制字符串的字节数类型 (BINARY,VARBINARYBLOB)。在为使用多字节字符集的非二元字符串列指定前缀长度时,请考虑这一点。Prefix limits are measured in bytes. However, prefix lengths for index specifications inCREATE TABLE,ALTER TABLE, andCREATE INDEXstatements are 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.该
exprfor akey_partspecification can take the form(CASTto create a multi-valued index on ajson_pathAStypeARRAY)JSONcolumn. Multi-Valued Indexes, provides detailed information regarding creation of, usage of, and restrictions and limitations on multi-valued indexes.Theexprfor akey_partspecification can take the form(CASTto create a multi-valued index on ajson_pathAStypeARRAY)JSONcolumn. Multi-Valued Indexes, provides detailed information regarding creation of, usage of, and restrictions and limitations on multi-valued indexes.
index_typeindex_type一些存储引擎允许您在创建索引时指定索引类型。语法为
index_typespecifier isUSING.Some storage engines permit you to specify an index type when creating an index. The syntax for thetype_nameindex_typespecifier isUSING.type_name示例:Example:
CREATE TABLE lookup (id INT, INDEX USING BTREE (id) ) ENGINE = MEMORY;
USING位于索引列列表之后。它可以放在列列表之前,但该位置对该选项的支持已被弃用,预计未来 MySQL 版本会移除。The preferred position forUSINGis 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 you should expect it to be removed in a future MySQL release.index_optionindex_optionvalues 为索引指定附加选项。index_optionvalues specify additional options for an index.KEY_BLOCK_SIZE对于
MyISAM表,KEY_BLOCK_SIZE可选地指定索引键块的字节大小。该值被视为提示;如有需要,可以使用不同的大小。KEY_BLOCK_SIZE为单个索引定义指定值,覆盖表级KEY_BLOCK_SIZE值。ForMyISAMtables,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.关于表级
KEY_BLOCK_SIZE,请参见 Table Options。For information about the table-levelKEY_BLOCK_SIZEattribute, see Table Options.WITH PARSERWITH PARSERWITH PARSER选项只能在FULLTEXT索引时使用。如果全文索引和搜索操作需要特殊处理,它会将解析器插件与索引关联。InnoDB和MyISAM支持全文解析器插件。如果你有MyISAM表及其关联的全文解析器插件,你可以使用InnoDB。TheWITH PARSERoption can be used only withFULLTEXTindexes. It associates a parser plugin with the index if full-text indexing and searching operations need special handling.InnoDBandMyISAMsupport full-text parser plugins. If you have aMyISAMtable with an associated full-text parser plugin, you can convert the table toInnoDBusingALTER TABLE.COMMENTCOMMENT索引定义可以包含最多 1024 个字符的可选注释。Index definitions can include an optional comment of up to 1024 characters.
你可以使用
InnoDB值。参见 第 17.8.11 节,“配置索引页合并阈值”。You can set theInnoDBMERGE_THRESHOLDvalue for an individual index using theindex_optionCOMMENTclause. See Section 17.8.11, “Configuring the Merge Threshold for Index Pages”.VISIBLE,INVISIBLEVISIBLE,INVISIBLE指定索引的可见性。索引默认是可见的。不可见索引不会被优化器使用。索引可见性的指定适用于主键以外的索引(无论显式还是隐式)。更多信息,请参见 第 10.3.12 节,“不可见索引”。Specify index visibility. Indexes are visible by default. An invisible index is not used by the optimizer. Specification of index visibility applies to indexes other than primary keys (either explicit or implicit). For more information, see Section 10.3.12, “Invisible Indexes”.
ENGINE_ATTRIBUTE和SECONDARY_ENGINE_ATTRIBUTE选项用于指定主存储和副存储引擎的索引属性。这些选项保留以供未来使用。ENGINE_ATTRIBUTEandSECONDARY_ENGINE_ATTRIBUTEoptions are used to specify index attributes for primary and secondary storage engines. The options are reserved for future use.
有关允许的
index_option值的更多信息,请参见第 15.1.15 节,“CREATE INDEX 语句”。有关索引的更多信息,请参见第 10.3.1 节,“MySQL 如何使用索引”.For more information about permissibleindex_optionvalues, see Section 15.1.15, “CREATE INDEX Statement”. For more information about indexes, see Section 10.3.1, “How MySQL Uses Indexes”.表,如果没有任何可变长度列(
reference_definitionsyntax details and examples, see Section 15.1.20.5, “FOREIGN KEY Constraints”.Forreference_definitionsyntax details and examples, see Section 15.1.20.5, “FOREIGN KEY Constraints”.InnoDB和NDB表支持检查外键约束。被引用表的列必须始终明确命名。支持ON DELETE和ON UPDATE对外键的操作。如需更详细的信息和示例,请参见 第 15.1.20.5 节,“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 15.1.20.5, “FOREIGN KEY Constraints”.对于其他存储引擎,MySQL Server 解析并忽略
FOREIGN KEY语法CREATE TABLE语句。For other storage engines, MySQL Server parses and ignores theFOREIGN KEYsyntax inCREATE TABLEstatements.Important对于熟悉 ANSI/ISO SQL 标准的用户请注意,任何存储引擎,包括
InnoDB,都不会识别或强制执行引用完整性约束定义中使用的MATCH子句。显式MATCH子句的使用不会产生指定的效果,并且会导致ON DELETE和ON UPDATE子句被忽略。因此,应避免指定MATCH。For users familiar with the ANSI/ISO SQL Standard, please note that no storage engine, includingInnoDB, recognizes or enforces theMATCHclause used in referential integrity constraint definitions. Use of an explicitMATCHclause does not have the specified effect, and also causesON DELETEandON UPDATEclauses to be ignored. For these reasons, specifyingMATCHshould be avoided.SQL 标准中的
MATCH子句控制了复合(多列)外键中NULL值与主键比较时的处理方式。InnoDB本质上实现了MATCH SIMPLE,允许外键为全部或部分NULL在这种情况下,包含此类外键的(子表)行允许插入,且不匹配被引用的(父)表中的任何行。也可以使用触发器实现其他语义。TheMATCHclause 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.此外,MySQL 要求引用列为索引以保证性能。然而,
InnoDB并不强制要求引用列必须声明为UNIQUE或NOT NULL对于包含NULL引用处理,对于诸如UPDATE或DELETE CASCADE。建议你使用只引用既是UNIQUE(或PRIMARY)又NOT NULL。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 解析但忽略了 “inline
REFERENCESspecifications”(根据 SQL 标准定义),该中引用作为列规范的一部分定义。MySQL 仅在作为独立REFERENCESMySQL parses but ignores “inlineREFERENCESspecifications” (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 more information, see Section 1.7.2.3, “FOREIGN KEY Constraint Differences”.有关
RESTRICT、CASCADE、SET NULLNO ACTION,以及SET DEFAULTOPTIONS,请参见 第 15.1.20.5 节,“FOREIGN KEY Constraints”。For information about theRESTRICT,CASCADE,SET NULL,NO ACTION, andSET DEFAULToptions, see Section 15.1.20.5, “FOREIGN KEY Constraints”.
表选项Table Options
表的选项用于优化表的行为。在大多数情况下,你无需指定任何选项。除非另有说明,这些选项适用于所有存储引擎。不适用于某一存储引擎的选项可能会被接受并作为表定义的一部分被记住。这些选项随后适用于你之后使用 ALTER TABLE来将表转换为使用不同的存储引擎时。Table options are used to optimize the behavior of the table. In
most cases, you do not have to specify any of them. These options
apply to all storage engines unless otherwise indicated. Options
that do not apply to a given storage engine may be accepted and
remembered as part of the table definition. Such options then
apply if you later use ALTER TABLE
to convert the table to use a different storage engine.
ENGINEENGINE指定表的存储引擎,使用下表中所示名称之一。引擎名称可为无引号或引号。引号名称
'DEFAULT'会被识别但被忽略。Specifies the storage engine for the table, using one of the names shown in the following table. The engine name can be unquoted or quoted. The quoted name'DEFAULT'is recognized but ignored.存储引擎Storage Engine 说明Description InnoDB支持事务的表,带行锁和外键。新表的默认存储引擎。参见第 17 章,InnoDB 存储引擎,尤其是第 17.1 节,“InnoDB 简介”如果你有 MySQL 经验但对新手 InnoDB.Transaction-safe tables with row locking and foreign keys. The default storage engine for new tables. See Chapter 17, The InnoDB Storage Engine, and in particular Section 17.1, “Introduction to InnoDB” if you have MySQL experience but are new toInnoDB.MyISAM主要用于只读或多读工作负载的二进制便携存储引擎。参见 第 18.2 节,“MyISAM 存储引擎”。The binary portable storage engine that is primarily used for read-only or read-mostly workloads. See Section 18.2, “The MyISAM Storage Engine”. MEMORYMEMORY该存储引擎的数据仅存储在内存中。参见 第 18.3 节,“内存存储引擎”。The data for this storage engine is stored only in memory. See Section 18.3, “The MEMORY Storage Engine”. CSV以逗号分隔值格式存储行的表。参见 第 18.4 节,“CSV 存储引擎”。Tables that store rows in comma-separated values format. See Section 18.4, “The CSV Storage Engine”. ARCHIVEARCHIVE归档存储引擎。参见 第 18.5 节,“ARCHIVE 存储引擎”。The archiving storage engine. See Section 18.5, “The ARCHIVE Storage Engine”. EXAMPLEEXAMPLE一个示例引擎。参见 第 18.9 节,“EXAMPLE 存储引擎”。An example engine. See Section 18.9, “The EXAMPLE Storage Engine”. FEDERATEDFEDERATEDStorage engine,访问远程表。参见 第 18.8 节,“FEDERATED 存储引擎”。Storage engine that accesses remote tables. See Section 18.8, “The FEDERATED Storage Engine”. HEAPHEAP这是 MEMORY词。This is a synonym forMEMORY.MERGEMERGE一组 MyISAM表作为一个表使用。也称为MRG_MyISAM。参见 第 18.7 节,“MERGE 存储引擎”。A collection ofMyISAMtables used as one table. Also known asMRG_MyISAM. See Section 18.7, “The MERGE Storage Engine”.NDBNDB集群、容错、基于内存的表,支持事务和外键。也称为 NDBCLUSTER参见 Chapter 25,MySQL NDB Cluster 8.4。Clustered, fault-tolerant, memory-based tables, supporting transactions and foreign keys. Also known asNDBCLUSTER. See Chapter 25, MySQL NDB Cluster 8.4.默认情况下,如果指定了不可用的存储引擎,则语句会失败并报错。可以通过从服务器 SQL 模式中删除
NO_ENGINE_SUBSTITUTION(参见第 7.1.11 节,“服务器 SQL 模式”)来覆盖此行为,使 MySQL 允许用默认存储引擎替代指定的存储引擎。通常在这种情况下,默认存储引擎是InnoDB,这是default_storage_engine系统变量的默认值。当NO_ENGINE_SUBSTITUTION被禁用时,如果未遵循存储引擎规范,将出现警告。By default, if a storage engine is specified that is not available, the statement fails with an error. You can override this behavior by removingNO_ENGINE_SUBSTITUTIONfrom the server SQL mode (see Section 7.1.11, “Server SQL Modes”) so that MySQL allows substitution of the specified engine with the default storage engine instead. Normally in such cases, this isInnoDB, which is the default value for thedefault_storage_enginesystem variable. WhenNO_ENGINE_SUBSTITUTIONis disabled, a warning occurs if the storage engine specification is not honored.AUTOEXTEND_SIZE定义当
InnoDB表空间满时扩展表空间大小的量。该设置必须是 4MB 的倍数。默认设置为 0,这会根据隐式默认行为扩展表空间。有关更多信息,请参见第 17.6.3.9 节,“表空间 AUTOEXTEND_SIZE 配置”。Defines the amount by whichInnoDBextends the size of the tablespace when it becomes full. The setting must be a multiple of 4MB. The default setting is 0, which causes the tablespace to be extended according to the implicit default behavior. For more information, see Section 17.6.3.9, “Tablespace AUTOEXTEND_SIZE Configuration”.AUTO_INCREMENT表的初始
AUTO_INCREMENT值。在 MySQL 8.4 中,这适用于MyISAM、MEMORY、InnoDB和ARCHIVE表。对于不支持AUTO_INCREMENT表选项的存储引擎,在创建表后,可插入一个值比所需值小一的 “dummy” 行,然后删除该 dummy 行,以设置第一个自增值。The initialAUTO_INCREMENTvalue for the table. In MySQL 8.4, this works forMyISAM,MEMORY,InnoDB, andARCHIVEtables. To set the first auto-increment value for engines that do not support theAUTO_INCREMENTtable option, insert a “dummy” row with a value one less than the desired value after creating the table, and then delete the dummy row.对于支持在
CREATE TABLE语句中使用AUTO_INCREMENT表选项的引擎,您也可以使用ALTER TABLE tbl_name AUTO_INCREMENT = N来重置AUTO_INCREMENT值。该值不能设置为低于当前列中的最大值。For engines that support theAUTO_INCREMENTtable option inCREATE TABLEstatements, you can also useALTER TABLEto reset thetbl_nameAUTO_INCREMENT =NAUTO_INCREMENTvalue. The value cannot be set lower than the maximum value currently in the column.AVG_ROW_LENGTH表中平均行长度的近似值。仅当表为具有可变大小行的大表时,才需要设置此值。An approximation of the average row length for your table. You need to set this only for large tables with variable-size rows.
当你创建一个
MyISAM表时,MySQL 会使用MAX_ROWS和AVG_ROW_LENGTH选项的乘积来决定生成表的大小。如果你没有指定任一选项,MyISAM数据和索引文件的最大默认大小为 256TB。(如果你的操作系统不支持如此大的文件,表的大小将受文件大小限制约束。)如果你想减少指针大小以使索引更小更快,并且你并不真正需要大文件,你可以通过设置myisam_data_pointer_size系统变量来降低默认指针大小。(参见 第 7.1.8 节“服务器系统变量”。)如果你希望所有表能够超过默认限制增长,并且愿意让表稍微变慢和占用更多空间,你可以通过设置该变量来增加默认指针大小。将值设置为 7 允许表大小最多达到 65,536TB。When you create aMyISAMtable, MySQL uses the product of theMAX_ROWSandAVG_ROW_LENGTHoptions to decide how big the resulting table is. If you don't specify either option, the maximum size forMyISAMdata and index files is 256TB by default. (If your operating system does not support files that large, table sizes are constrained by the file size limit.) If you want to keep down the pointer sizes to make the index smaller and faster and you don't really need big files, you can decrease the default pointer size by setting themyisam_data_pointer_sizesystem variable. (See Section 7.1.8, “Server System Variables”.) If you want all your tables to be able to grow above the default limit and are willing to have your tables slightly slower and larger than necessary, you can increase the default pointer size by setting this variable. Setting the value to 7 permits table sizes up to 65,536TB.[DEFAULT] CHARACTER SET指定表的默认字符集。
CHARSET是CHARACTER SET的同义词。如果字符集名称为DEFAULT,则使用数据库字符集。Specifies a default character set for the table.CHARSETis a synonym forCHARACTER SET. If the character set name isDEFAULT, the database character set is used.CHECKSUMCHECKSUM如果你希望 MySQL 为所有行维护实时校验和(即表发生变化时 MySQL 自动更新的校验和),请将其设置为 1。这会使表的更新稍慢,但也使查找损坏表更容易。
CHECKSUM TABLE语句报告校验和。(仅适用于MyISAM。)Set this to 1 if you want MySQL to maintain a live checksum for all rows (that is, a checksum that MySQL updates automatically as the table changes). This makes the table a little slower to update, but also makes it easier to find corrupted tables. TheCHECKSUM TABLEstatement reports the checksum. (MyISAMonly.)[DEFAULT] COLLATE为表指定默认排序规则。Specifies a default collation for the table.
COMMENTCOMMENT表的注释,最长可达 2048 个字符。A comment for the table, up to 2048 characters long.
您可以使用
table_optionCOMMENT子句为表设置InnoDBMERGE_THRESHOLD值。请参见 第 17.8.11 节,“配置索引页的合并阈值”。You can set theInnoDBMERGE_THRESHOLDvalue for a table using thetable_optionCOMMENTclause. See Section 17.8.11, “Configuring the Merge Threshold for Index Pages”.设置 NDB_TABLE 选项。 在创建
NDB表的CREATE TABLE中,或者在修改表的ALTER TABLE语句中,表注释也可以用来指定一个到四个NDB_TABLE选项,即NOLOGGING、READ_BACKUP、PARTITION_BALANCE或FULLY_REPLICATED,作为一组名称-值对,如有需要用逗号分隔,紧跟在以NDB_TABLE=开头的引号注释文本之后。下面显示了使用此语法的示例语句(加粗文本):Setting NDB_TABLE options. The table comment in aCREATE TABLEthat creates anNDBtable or anALTER TABLEstatement which alters one can also be used to specify one to four of theNDB_TABLEoptionsNOLOGGING,READ_BACKUP,PARTITION_BALANCE, orFULLY_REPLICATEDas a set of name-value pairs, separated by commas if need be, immediately following the stringNDB_TABLE=that begins the quoted comment text. An example statement using this syntax is shown here (emphasized text):CREATE TABLE t1 ( c1 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, c2 VARCHAR(100), c3 VARCHAR(100) ) ENGINE=NDB COMMENT="NDB_TABLE=READ_BACKUP=0,PARTITION_BALANCE=FOR_RP_BY_NODE";引号内的字符串不允许有空格。字符串不区分大小写。Spaces are not permitted within the quoted string. The string is case-insensitive.
该注释作为
SHOW CREATE TABLE输出的一部分显示。注释的文本也可以通过 MySQL 信息模式的TABLES表的 TABLE_COMMENT 列获得。The comment is displayed as part of the output ofSHOW CREATE TABLE. The text of the comment is also available as the TABLE_COMMENT column of the MySQL Information SchemaTABLEStable.此注释语法也支持
ALTER TABLE语句用于NDB表。请注意,与ALTER TABLE一起使用的表注释会替换表先前可能已有的任何现有注释。This comment syntax is also supported withALTER TABLEstatements forNDBtables. Keep in mind that a table comment used withALTER TABLEreplaces any existing comment which the table might have had previously.在表注释中设置
MERGE_THRESHOLD选项不支持NDB表(该选项将被忽略)。Setting theMERGE_THRESHOLDoption in table comments is not supported forNDBtables (it is ignored).有关完整的语法信息和示例,请参见 第 15.1.20.12 节,“设置 NDB 注释选项”。For complete syntax information and examples, see Section 15.1.20.12, “Setting NDB Comment Options”.
COMPRESSIONCOMPRESSION用于
InnoDB表页面级压缩的压缩算法。支持的值包括Zlib、LZ4和None。COMPRESSION属性是随着透明页面压缩功能引入的。页面压缩仅支持位于 file-per-table 表空间的InnoDB表,并且仅在支持稀疏文件和孔打孔的 Linux 和 Windows 平台上可用。有关更多信息,请参见 第 17.9.2 节,“InnoDB 页面压缩”。The compression algorithm used for page level compression forInnoDBtables. Supported values includeZlib,LZ4, andNone. TheCOMPRESSIONattribute was introduced with the transparent page compression feature. Page compression is only supported withInnoDBtables that reside in file-per-table tablespaces, and is only available on Linux and Windows platforms that support sparse files and hole punching. For more information, see Section 17.9.2, “InnoDB Page Compression”.CONNECTIONCONNECTIONFEDERATED表的连接字符串。The connection string for aFEDERATEDtable.Note旧版本的 MySQL 使用
COMMENT选项作为连接字符串。Older versions of MySQL used aCOMMENToption for the connection string.DATA DIRECTORY,INDEX DIRECTORYDATA DIRECTORY,INDEX DIRECTORY对于
InnoDB,DATA DIRECTORY='directory'子句允许在数据目录之外创建表。必须启用innodb_file_per_table变量才能使用DATA DIRECTORY子句。必须指定完整的目录路径,并为InnoDB所知。有关更多信息,请参见 第 17.6.1.2 节,“外部创建表”。ForInnoDB, theDATA DIRECTORY='clause permits creating tables outside of the data directory. Thedirectory'innodb_file_per_tablevariable must be enabled to use theDATA DIRECTORYclause. The full directory path must be specified, and known toInnoDB. For more information, see Section 17.6.1.2, “Creating Tables Externally”.在创建
MyISAM,你可以使用DATA DIRECTORY='directory'子句,INDEX DIRECTORY='directory'子句,或者两者兼用。它们指定了MyISAM表的数据文件和索引文件。与InnoDB,MySQL 在创建MyISAM,同时使用DATA DIRECTORY或INDEX DIRECTORY选项。文件是在指定的目录中创建的。When creatingMyISAMtables, you can use theDATA DIRECTORY='clause, thedirectory'INDEX DIRECTORY='clause, or both. They specify where to put adirectory'MyISAMtable's data file and index file, respectively. UnlikeInnoDBtables, MySQL does not create subdirectories that correspond to the database name when creating aMyISAMtable with aDATA DIRECTORYorINDEX DIRECTORYoption. Files are created in the directory that is specified.你必须拥有
FILE权限,才能使用DATA DIRECTORY或INDEX DIRECTORY表格选项。You must have theFILEprivilege to use theDATA DIRECTORYorINDEX DIRECTORYtable option.Important表格级
DATA DIRECTORY和INDEX DIRECTORY选项在分区表中被忽略。(错误 #32091)Table-levelDATA DIRECTORYandINDEX DIRECTORYoptions are ignored for partitioned tables. (Bug #32091)这些选项仅在你未使用
--skip-symbolic-links选项时有效。你的操作系统还必须有一个可用的、线程安全的realpath()调用。详见 第 10.12.2.2 节,“使用 MyISAM 表的符号链接”,以获取更完整的信息。These options work only when you are not using the--skip-symbolic-linksoption. Your operating system must also have a working, thread-saferealpath()call. See Section 10.12.2.2, “Using Symbolic Links for MyISAM Tables on Unix”, for more complete information.如果创建的
MyISAM表没有DATA DIRECTORY,则.MYD文件会在数据库目录中创建。默认情况下,如果MyISAM找到已有的.MYD文件会覆盖该文件。同样的情况也适用于.MYI对于没有INDEX DIRECTORY。为抑制此行为,服务器启动时设置--keep_files_on_create选项,此时MyISAM不会覆盖现有文件,而是返回错误。If aMyISAMtable is created with noDATA DIRECTORYoption, the.MYDfile is created in the database directory. By default, ifMyISAMfinds an existing.MYDfile in this case, it overwrites it. The same applies to.MYIfiles for tables created with noINDEX DIRECTORYoption. To suppress this behavior, start the server with the--keep_files_on_createoption, in which caseMyISAMdoes not overwrite existing files and returns an error instead.如果创建了
MyISAM表,则使用DATA DIRECTORY,或INDEX DIRECTORY选项,以及现有的.MYD或.MYI文件时,MyISAM总是返回错误,且不会覆盖指定目录中的文件。If aMyISAMtable is created with aDATA DIRECTORYorINDEX DIRECTORYoption and an existing.MYDor.MYIfile is found,MyISAMalways returns an error, and does not overwrite a file in the specified directory.Important你不能使用包含 MySQL 数据目录的路径名,使用
DATA DIRECTORY或INDEX DIRECTORY。这包括分区表和单个表分区。(参见 Bug #32167。)You cannot use path names that contain the MySQL data directory withDATA DIRECTORYorINDEX DIRECTORY. This includes partitioned tables and individual table partitions. (See Bug #32167.)DELAY_KEY_WRITEDELAY_KEY_WRITE如果你想延迟表的密钥更新直到表关闭,请将其设为 1。请参见
delay_key_write系统变量的描述,第 7.1.8 节,“Server System Variables”。(MyISAM。)Set this to 1 if you want to delay key updates for the table until the table is closed. See the description of thedelay_key_writesystem variable in Section 7.1.8, “Server System Variables”. (MyISAMonly.)ENCRYPTIONENCRYPTIONENCRYPTION子句用于启用或禁用InnoDB表的页面级数据加密。在启用加密之前,必须安装和配置 keyring 插件。ENCRYPTION子句可以在创建文件表空间中的表时指定,也可以在创建通用表空间中的表时指定。TheENCRYPTIONclause enables or disables page-level data encryption for anInnoDBtable. A keyring plugin must be installed and configured before encryption can be enabled. TheENCRYPTIONclause can be specified when creating a table in an a file-per-table tablespace, or when creating a table in a general tablespace.ENCRYPTION选项仅受InnoDB存储引擎支持;因此,它仅在默认存储引擎为InnoDB时,或者CREATE TABLE语句也指定ENGINE=InnoDB时有效。否则,该语句将被拒绝,并返回ER_CHECK_NOT_IMPLEMENTED错误。TheENCRYPTIONoption is supported only by theInnoDBstorage engine; thus it works only if the default storage engine isInnoDB, or if theCREATE TABLEstatement also specifiesENGINE=InnoDB. Otherwise the statement is rejected withER_CHECK_NOT_IMPLEMENTED.表继承默认模式加密,且
ENCRYPTION未指定某子句。如果table_encryption_privilege_check该变量被启用,TABLE_ENCRYPTION_ADMIN则需要该权限创建与ENCRYPTION默认模式加密不同的子句设置表。在创建通用表空间的表时,表和表空间的加密必须匹配。A table inherits the default schema encryption if anENCRYPTIONclause is not specified. If thetable_encryption_privilege_checkvariable is enabled, theTABLE_ENCRYPTION_ADMINprivilege is required to create a table with anENCRYPTIONclause setting that differs from the default schema encryption. When creating a table in a general tablespace, table and tablespace encryption must match.在使用不支持加密的存储引擎时,不允许指定除了
'N'或''之外的ENCRYPTION子句值。Specifying anENCRYPTIONclause with a value other than'N'or''is not permitted when using a storage engine that does not support encryption.有关更多信息,请参见第 17.13 节,“InnoDB 静态数据加密”。For more information, see Section 17.13, “InnoDB Data-at-Rest Encryption”.
ENGINE_ATTRIBUTE和SECONDARY_ENGINE_ATTRIBUTE选项用于指定主存储引擎和辅助存储引擎的表属性。这些选项为将来使用保留。TheENGINE_ATTRIBUTEandSECONDARY_ENGINE_ATTRIBUTEoptions are used to specify table attributes for primary and secondary storage engines. The options are reserved for future use.分配给这两个选项中的任意一个的值必须是包含有效 JSON 文档的字符串字面量,或者是空字符串 ('')。无效的 JSON 将被拒绝。The value assigned to either of these options must be a string literal containing a valid JSON document or an empty string (''). Invalid JSON is rejected.
CREATE TABLE t1 (c1 INT) ENGINE_ATTRIBUTE='{"key":"value"}';ENGINE_ATTRIBUTE和SECONDARY_ENGINE_ATTRIBUTE的值可以重复而不会出错。在这种情况下,将使用最后指定的值。ENGINE_ATTRIBUTEandSECONDARY_ENGINE_ATTRIBUTEvalues can be repeated without error. In this case, the last specified value is used.ENGINE_ATTRIBUTE和SECONDARY_ENGINE_ATTRIBUTE的值不会被服务器检查,也不会在更改表的存储引擎时清除。ENGINE_ATTRIBUTEandSECONDARY_ENGINE_ATTRIBUTEvalues are not checked by the server, nor are they cleared when the table's storage engine is changed.INSERT_METHODINSERT_METHOD如果你想将数据插入到
MERGE表中,必须用INSERT_METHOD该行应插入的表。INSERT_METHOD是仅适用于MERGE表的选项。使用FIRST或LAST来让插入进入第一个或最后一个表,或者使用NO来防止插入。参见 第 18.7 节,“MERGE 存储引擎”。If you want to insert data into aMERGEtable, you must specify withINSERT_METHODthe table into which the row should be inserted.INSERT_METHODis an option useful forMERGEtables only. Use a value ofFIRSTorLASTto have inserts go to the first or last table, or a value ofNOto prevent inserts. See Section 18.7, “The MERGE Storage Engine”.KEY_BLOCK_SIZE对于
MyISAM表,KEY_BLOCK_SIZE可选地指定索引键块的字节大小。该值被视为提示;如有需要,可以使用不同的大小。KEY_BLOCK_SIZE为单个索引定义指定值,覆盖表级KEY_BLOCK_SIZE值。ForMyISAMtables,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.表,如果没有任何可变长度列(
InnoDBtables,KEY_BLOCK_SIZEspecifies the page size in kilobytes to use for compressedInnoDBtables. TheKEY_BLOCK_SIZEvalue is treated as a hint; a different size could be used byInnoDBif necessary.KEY_BLOCK_SIZEcan only be less than or equal to theinnodb_page_sizevalue. A value of 0 represents the default compressed page size, which is half of theinnodb_page_sizevalue. Depending oninnodb_page_size, possibleKEY_BLOCK_SIZEvalues include 0, 1, 2, 4, 8, and 16. See Section 17.9.1, “InnoDB Table Compression” for more information.ForInnoDBtables,KEY_BLOCK_SIZEspecifies the page size in kilobytes to use for compressedInnoDBtables. TheKEY_BLOCK_SIZEvalue is treated as a hint; a different size could be used byInnoDBif necessary.KEY_BLOCK_SIZEcan only be less than or equal to theinnodb_page_sizevalue. A value of 0 represents the default compressed page size, which is half of theinnodb_page_sizevalue. Depending oninnodb_page_size, possibleKEY_BLOCK_SIZEvalues include 0, 1, 2, 4, 8, and 16. See Section 17.9.1, “InnoDB Table Compression” for more information.Oracle 建议在指定
innodb_strict_mode用于InnoDB。当启用innodb_strict_mode时,指定无效的KEY_BLOCK_SIZE值会返回错误。如果innodb_strict_mode被禁用,则无效的KEY_BLOCK_SIZE值会触发警告,KEY_BLOCK_SIZE选项将被忽略。Oracle recommends enablinginnodb_strict_modewhen specifyingKEY_BLOCK_SIZEforInnoDBtables. Wheninnodb_strict_modeis enabled, specifying an invalidKEY_BLOCK_SIZEvalue returns an error. Ifinnodb_strict_modeis disabled, an invalidKEY_BLOCK_SIZEvalue results in a warning, and theKEY_BLOCK_SIZEoption is ignored.Create_options列,作为SHOW TABLE STATUS报告表实际使用的实际KEY_BLOCK_SIZE,SHOW CREATE TABLE”。TheCreate_optionscolumn in response toSHOW TABLE STATUSreports the actualKEY_BLOCK_SIZEused by the table, as doesSHOW CREATE TABLE.InnoDB仅支持KEY_BLOCK_SIZE在表层面。InnoDBonly supportsKEY_BLOCK_SIZEat the table level.KEY_BLOCK_SIZE不支持 32KB 和 64KB 的innodb_page_size值。InnoDB表压缩不支持这些页面大小。KEY_BLOCK_SIZEis not supported with 32KB and 64KBinnodb_page_sizevalues.InnoDBtable compression does not support these pages sizes.InnoDB在创建临时表时不支持KEY_BLOCK_SIZE选项。InnoDBdoes not support theKEY_BLOCK_SIZEoption when creating temporary tables.MAX_ROWSMAX_ROWS你计划在表中存储的最大行数。这不是一个硬性限制,而是给存储引擎的一个提示,表必须能够至少存储这么多行。The maximum number of rows you plan to store in the table. This is not a hard limit, but rather a hint to the storage engine that the table must be able to store at least this many rows.
Important使用
MAX_ROWS配合NDB表来控制表分区数量已被弃用。该功能在后续版本中仍支持以实现向后兼容,但未来版本可能会被移除。请改用 PARTITION_BALANCE;参见 Setting NDB_TABLE options“。The use ofMAX_ROWSwithNDBtables to control the number of table partitions is deprecated. It remains supported in later versions for backward compatibility, but is subject to removal in a future release. Use PARTITION_BALANCE instead; see Setting NDB_TABLE options.NDB存储引擎将该值视为最大值。如果你计划创建非常大的 NDB 集群表(包含数百万行),你应该使用这个选项确保NDB在用于存储表主键哈希的哈希表中分配足够的索引槽,方法是设置MAX_ROWS = 2 * rows其中rows你预计插入到表中的行数。TheNDBstorage engine treats this value as a maximum. If you plan to create very large NDB Cluster tables (containing millions of rows), you should use this option to insure thatNDBallocates sufficient number of index slots in the hash table used for storing hashes of the table's primary keys by settingMAX_ROWS = 2 *, whererowsrowsis the number of rows that you expect to insert into the table.最大
MAX_ROWS值为 4294967295;更大的值会被截断到这个限制。The maximumMAX_ROWSvalue is 4294967295; larger values are truncated to this limit.MIN_ROWSMIN_ROWS你计划在表中存储的最小行数。
MEMORYstorage engine 使用此选项作为内存使用提示。The minimum number of rows you plan to store in the table. TheMEMORYstorage engine uses this option as a hint about memory use.PACK_KEYSPACK_KEYS仅在
MyISAM。如果你想让索引更小,将此选项设为 1。这通常会使更新变慢,读取更快。将选项设置为 0 会禁用所有密钥打包。将其设置为DEFAULT会让存储引擎只打包长CHAR,VARCHARBINARY或者VARBINARY列。Takes effect only withMyISAMtables. Set this option to 1 if you want to have smaller indexes. This usually makes updates slower and reads faster. Setting the option to 0 disables all packing of keys. Setting it toDEFAULTtells the storage engine to pack only longCHAR,VARCHAR,BINARY, orVARBINARYcolumns.如果你不使用
PACK_KEYS,默认是打包字符串,但不打包数字。如果你使用PACK_KEYS=1,数字也会被打包。If you do not usePACK_KEYS, the default is to pack strings, but not numbers. If you usePACK_KEYS=1, numbers are packed as well.在打包二进制数字键时,MySQL 使用前缀压缩:When packing binary number keys, MySQL uses prefix compression:
每个键都需要额外一个字节来指示前一个键有多少字节与下一个键相同。Every key needs one extra byte to indicate how many bytes of the previous key are the same for the next key.
行指针以高字节优先的顺序直接存储在键之后,以提高压缩率。The pointer to the row is stored in high-byte-first order directly after the key, to improve compression.
这意味着如果你在两行连续的行上有许多相同的键,则所有后续的“相同”键通常只占用两个字节(包括指向该行的指针)。与普通情况下后续键占用
storage_size_for_key + pointer_size(其中指针大小通常为 4)相比。相反,只有当你有许多相同的数字时,从前缀压缩中才能获得显著的好处。如果所有键完全不同,则每个键会额外使用一个字节,如果该键不是可以有NULL值的键。(在这种情况下,打包键的长度存储在用于标记键是否为NULL的同一个字节中。)This means that if you have many equal keys on two consecutive rows, all following “same” keys usually only take two bytes (including the pointer to the row). Compare this to the ordinary case where the following keys takesstorage_size_for_key + pointer_size(where the pointer size is usually 4). Conversely, you get a significant benefit from prefix compression only if you have many numbers that are the same. If all keys are totally different, you use one byte more per key, if the key is not a key that can haveNULLvalues. (In this case, the packed key length is stored in the same byte that is used to mark if a key isNULL.)PASSWORDPASSWORD此选项未使用。This option is unused.
ROW_FORMATROW_FORMAT定义行存储的物理格式。Defines the physical format in which the rows are stored.
在创建禁用严格模式的表时,如果指定的行格式不受支持,则使用存储引擎的默认行格式。表的实际行格式会在
Row_format的SHOW TABLE STATUS列中显示。Create_options列显示在CREATE TABLE语句中指定的行格式,SHOW CREATE TABLE也是如此。When creating a table with strict mode disabled, the storage engine's default row format is used if the specified row format is not supported. The actual row format of the table is reported in theRow_formatcolumn in response toSHOW TABLE STATUS. TheCreate_optionscolumn shows the row format that was specified in theCREATE TABLEstatement, as doesSHOW CREATE TABLE.行格式的选择取决于表使用的存储引擎。Row format choices differ depending on the storage engine used for the table.
对于
InnoDB表:ForInnoDBtables:默认行格式由
innodb_default_row_format定义,默认设置为DYNAMIC。当未定义ROW_FORMAT选项或使用ROW_FORMAT=DEFAULT时,将使用默认行格式。The default row format is defined byinnodb_default_row_format, which has a default setting ofDYNAMIC. The default row format is used when theROW_FORMAToption is not defined or whenROW_FORMAT=DEFAULTis used.如果未定义
ROW_FORMAT选项,或者使用ROW_FORMAT=DEFAULT,重建表的操作也会默默地将表的行格式更改为innodb_default_row_format定义的默认值。更多信息,请参见定义表的行格式。If theROW_FORMAToption is not defined, or ifROW_FORMAT=DEFAULTis used, operations that rebuild a table also silently change the row format of the table to the default defined byinnodb_default_row_format. For more information, see Defining the Row Format of a Table.为了更高效地存储
InnoDB数据类型,尤其是BLOB类型,请使用DYNAMIC。有关DYNAMIC行格式的要求,请参见DYNAMIC 行格式。For more efficientInnoDBstorage of data types, especiallyBLOBtypes, use theDYNAMIC. See DYNAMIC Row Format for requirements associated with theDYNAMICrow format.要启用
InnoDB表的压缩,请指定ROW_FORMAT=COMPRESSED。在创建临时表时,不支持ROW_FORMAT=COMPRESSED选项。有关COMPRESSED行格式的要求,请参见第 17.9 节,“InnoDB 表和页压缩”。To enable compression forInnoDBtables, specifyROW_FORMAT=COMPRESSED. TheROW_FORMAT=COMPRESSEDoption is not supported when creating temporary tables. See Section 17.9, “InnoDB Table and Page Compression” for requirements associated with theCOMPRESSEDrow format.可以通过指定
REDUNDANT行格式,请求使用旧版本 MySQL 中使用的行格式。The row format used in older versions of MySQL can still be requested by specifying theREDUNDANTrow format.当您指定非默认的
ROW_FORMAT子句时,也请考虑启用innodb_strict_mode配置选项。When you specify a non-defaultROW_FORMATclause, consider also enabling theinnodb_strict_modeconfiguration option.ROW_FORMAT=FIXED不受支持。如果在禁用innodb_strict_mode时指定ROW_FORMAT=FIXED,InnoDB将发出警告并假定ROW_FORMAT=DYNAMIC。如果在启用(默认)的innodb_strict_mode时指定ROW_FORMAT=FIXED,InnoDB将返回错误。ROW_FORMAT=FIXEDis not supported. IfROW_FORMAT=FIXEDis specified whileinnodb_strict_modeis disabled,InnoDBissues a warning and assumesROW_FORMAT=DYNAMIC. IfROW_FORMAT=FIXEDis specified whileinnodb_strict_modeis enabled, which is the default,InnoDBreturns an error.有关
InnoDB行格式的更多信息,请参见第 17.10 节,“InnoDB 行格式”。For additional information aboutInnoDBrow formats, see Section 17.10, “InnoDB Row Formats”.
对于
MyISAM表,选项值可以是FIXED或DYNAMIC,适用于静态或可变长度的行格式。myisampack 将类型设置为COMPRESSED。参见 第 18.2.3 节,“MyISAM 表存储格式”。ForMyISAMtables, the option value can beFIXEDorDYNAMICfor static or variable-length row format. myisampack sets the type toCOMPRESSED. See Section 18.2.3, “MyISAM Table Storage Formats”.对于
NDB表,默认的ROW_FORMAT为DYNAMICForNDBtables, the defaultROW_FORMATisDYNAMIC.START TRANSACTIONSTART TRANSACTION这是一个内部使用表选项,用于允许
CREATE TABLE ... SELECT在使用支持原子 DDL 的基于行的复制时,SELECT 作为单一原子事务记录在二进制日志中。只有BINLOG,COMMIT, andROLLBACK语句在CREATE TABLE ... START TRANSACTION相关信息请参见 第 15.1.1 节,“原子数据定义语句支持”。This is an internal-use table option, used to permitCREATE TABLE ... SELECTto be logged as a single, atomic transaction in the binary log when using row-based replication with a storage engine that supports atomic DDL. OnlyBINLOG,COMMIT, andROLLBACKstatements are permitted afterCREATE TABLE ... START TRANSACTION. For related information, see Section 15.1.1, “Atomic Data Definition Statement Support”.STATS_AUTO_RECALC指定是否自动重新计算 persistent stats,适用于
InnoDB表。值DEFAULT使得表的持久统计设置由innodb_stats_auto_recalc配置选项决定。值1在表中 10% 数据发生变化时,统计数据会被重新计算。0阻止该表的自动重新计算;在此设置下,执行ANALYZE TABLE语句,在对表做重大修改后重新计算统计数据。有关持久统计功能的更多信息,请参见 第 17.8.10.1 节,“配置持久优化器统计参数”。Specifies whether to automatically recalculate persistent statistics for anInnoDBtable. The valueDEFAULTcauses the persistent statistics setting for the table to be determined by theinnodb_stats_auto_recalcconfiguration option. The value1causes statistics to be recalculated when 10% of the data in the table has changed. The value0prevents automatic recalculation for this table; with this setting, issue anANALYZE TABLEstatement to recalculate the statistics after making substantial changes to the table. For more information about the persistent statistics feature, see Section 17.8.10.1, “Configuring Persistent Optimizer Statistics Parameters”.STATS_PERSISTENT指定是否启用 persistent stats,用于
InnoDB表。值DEFAULT使得表的持久统计设置由innodb_stats_persistent配置选项决定。值1使表的持久统计成为可能,而0则关闭此功能。在通过CREATE TABLE或ALTER TABLE后,在将代表性数据加载到表中后,发布ANALYZE TABLE语句来计算统计数据,并加载代表性数据到表中。有关持久统计功能的更多信息,请参见 第 17.8.10.1 节,“配置持久优化器统计参数”。Specifies whether to enable persistent statistics for anInnoDBtable. The valueDEFAULTcauses the persistent statistics setting for the table to be determined by theinnodb_stats_persistentconfiguration option. The value1enables persistent statistics for the table, while the value0turns off this feature. After enabling persistent statistics through aCREATE TABLEorALTER TABLEstatement, issue anANALYZE TABLEstatement to calculate the statistics, after loading representative data into the table. For more information about the persistent statistics feature, see Section 17.8.10.1, “Configuring Persistent Optimizer Statistics Parameters”.STATS_SAMPLE_PAGES在估计索引列的基数和其他统计时,需要采样的索引页数量,例如由
ANALYZE TABLE更多信息请参见 第 17.8.10.1 节,“配置持久优化器统计参数”。The number of index pages to sample when estimating cardinality and other statistics for an indexed column, such as those calculated byANALYZE TABLE. For more information, see Section 17.8.10.1, “Configuring Persistent Optimizer Statistics Parameters”.TABLESPACETABLESPACETABLESPACE子句可用于创建InnoDB表,适用于现有的通用表空间、逐文件表空间或系统表空间。TheTABLESPACEclause can be used to create anInnoDBtable in an existing general tablespace, a file-per-table tablespace, or the system tablespace.CREATE TABLE
tbl_name... TABLESPACE [=]tablespace_name你指定的通用表空间必须在使用
TABLESPACE子句之前存在。有关一般表空间的信息,请参见 第 17.6.3.3 节,“通用表空间”。The general tablespace that you specify must exist prior to using theTABLESPACEclause. For information about general tablespaces, see Section 17.6.3.3, “General Tablespaces”.该
is a case-sensitive identifier. It may be quoted or unquoted. The forward slash character (“/”) is not permitted. Names beginning with “innodb_” are reserved for special use.Thetablespace_nameis a case-sensitive identifier. It may be quoted or unquoted. The forward slash character (“/”) is not permitted. Names beginning with “innodb_” are reserved for special use.tablespace_name要在系统表空间中创建表,请指定
innodb_system作为表空间名称。To create a table in the system tablespace, specifyinnodb_systemas the tablespace name.CREATE TABLE
tbl_name... TABLESPACE [=] innodb_system使用
TABLESPACE [=] innodb_system,你可以在系统表空间中放置任意未压缩行格式的表,而不考虑innodb_file_per_table设置。例如,你可以使用ROW_FORMAT=DYNAMIC。UsingTABLESPACE [=] innodb_system, you can place a table of any uncompressed row format in the system tablespace regardless of theinnodb_file_per_tablesetting. For example, you can add a table withROW_FORMAT=DYNAMICto the system tablespace usingTABLESPACE [=] innodb_system.要在逐表文件表空间创建表,表空间名称指定为
innodb_file_per_table。To create a table in a file-per-table tablespace, specifyinnodb_file_per_tableas the tablespace name.CREATE TABLE
tbl_name... TABLESPACE [=] innodb_file_per_tableNote如果启用了
innodb_file_per_table,则无需指定TABLESPACE=innodb_file_per_table即可创建InnoDB文件每表空间。InnoDB表默认在每个表文件中创建,当innodb_file_per_table时。Ifinnodb_file_per_tableis enabled, you need not specifyTABLESPACE=innodb_file_per_tableto create anInnoDBfile-per-table tablespace.InnoDBtables are created in file-per-table tablespaces by default wheninnodb_file_per_tableis enabled.DATA DIRECTORY子句允许,CREATE TABLE ... TABLESPACE=innodb_file_per_table,但不支持与TABLESPACE。DATA DIRECTORY子句中指定的目录必须已知InnoDB。更多信息请参见 Using the DATA DIRECTORY Clause。TheDATA DIRECTORYclause is permitted withCREATE TABLE ... TABLESPACE=innodb_file_per_tablebut is otherwise not supported for use in combination with theTABLESPACEclause. The directory specified in aDATA DIRECTORYclause must be known toInnoDB. For more information, see Using the DATA DIRECTORY Clause.Note支持
TABLESPACE = innodb_file_per_table和TABLESPACE = innodb_temporary子句,CREATE TEMPORARY TABLE弃用;预计未来版本的 MySQL 会移除。Support forTABLESPACE = innodb_file_per_tableandTABLESPACE = innodb_temporaryclauses withCREATE TEMPORARY TABLEis deprecated; expect it to be removed in a future version of MySQL.STORAGEtable 选项仅用于NDB表。STORAGE决定所使用的存储类型,可以是DISK或MEMORY。TheSTORAGEtable option is employed only withNDBtables.STORAGEdetermines the type of storage used, and can be either ofDISKorMEMORY.TABLESPACE ... STORAGE DISK将表分配到 NDB 集群磁盘表空间。STORAGE DISK前置于,CREATE TABLE否则不可使用TABLESPACEtablespace_name.TABLESPACE ... STORAGE DISKassigns a table to an NDB Cluster Disk Data tablespace.STORAGE DISKcannot be used inCREATE TABLEunless preceded byTABLESPACEtablespace_name.表,如果没有任何可变长度列(
STORAGE MEMORY, the tablespace name is optional, thus, you can useTABLESPACEor simplytablespace_nameSTORAGE MEMORYSTORAGE MEMORYto specify explicitly that the table is in-memory.ForSTORAGE MEMORY, the tablespace name is optional, thus, you can useTABLESPACEor simplytablespace_nameSTORAGE MEMORYSTORAGE MEMORYto specify explicitly that the table is in-memory.更多信息请参见 第 25.6.11 节,“NDB 集群磁盘表”。See Section 25.6.11, “NDB Cluster Disk Data Tables”, for more information.
用于访问一组相同的
MyISAM表集合。这仅适用于MERGE表。参见 第 18.7 节,“MERGE 存储引擎”。Used to access a collection of identicalMyISAMtables as one. This works only withMERGEtables. See Section 18.7, “The MERGE Storage Engine”.You must have
SELECT,UPDATE,以及DELETEprivileges for the tables you map to aMERGE权限。You must haveSELECT,UPDATE, andDELETEprivileges for the tables you map to aMERGEtable.Note以前,所有使用的表都必须与
MERGE。但现在这一限制不再适用。Formerly, all tables used had to be in the same database as theMERGEtable itself. This restriction no longer applies.
表分区Table Partitioning
partition_options来控制创建的表的分区CREATE TABLE.partition_options can be used to
control partitioning of the table created with
CREATE TABLE.
Not all options shown in the syntax for
partition_options at the beginning of
this section are available for all partitioning types. Please see
the listings for the following individual types for information
specific to each type, and see Chapter 26, 分区, for
more complete information about the workings of and uses for
partitioning in MySQL, as well as additional examples of table
creation and other statements relating to MySQL partitioning.Not all options shown in the syntax for
partition_options at the beginning of
this section are available for all partitioning types. Please see
the listings for the following individual types for information
specific to each type, and see Chapter 26, Partitioning, for
more complete information about the workings of and uses for
partitioning in MySQL, as well as additional examples of table
creation and other statements relating to MySQL partitioning.
分区可以被修改、合并、添加到表中,也可以从表中丢弃。有关完成这些任务的 MySQL 语句的基本信息,请参见 第 15.1.9 节,”ALTER TABLE Statement“。如需更详细的描述和示例,请参见 第 26.3 节,“Partition Management”。Partitions can be modified, merged, added to tables, and dropped from tables. For basic information about the MySQL statements to accomplish these tasks, see Section 15.1.9, “ALTER TABLE Statement”. For more detailed descriptions and examples, see Section 26.3, “Partition Management”.
PARTITION BYPARTITION BYIf used, a
partition_optionsclause begins withPARTITION BY. This clause contains the function that is used to determine the partition; the function returns an integer value ranging from 1 tonum,其中numis the number of partitions. (The maximum number of user-defined partitions which a table may contain is 1024; the number of subpartitions—discussed later in this section—is included in this maximum.)If used, apartition_optionsclause begins withPARTITION BY. This clause contains the function that is used to determine the partition; the function returns an integer value ranging from 1 tonum, wherenumis the number of partitions. (The maximum number of user-defined partitions which a table may contain is 1024; the number of subpartitions—discussed later in this section—is included in this maximum.)Noteexpr不能引用创建表中未列的列;此类引用明确不允许,会导致语句错误失败。(漏洞#29444)The expression (expr) used in aPARTITION BYclause cannot refer to any columns not in the table being created; such references are specifically not permitted and cause the statement to fail with an error. (Bug #29444)HASH(expr)HASH(expr)对一个或多个列进行哈希,生成用于放置和定位行的键。
expr是使用一个或多个表列的表达式。这可以是任何有效的 MySQL 表达式(包括 MySQL 函数),只要能得到一个整数值。例如,这两个都有效CREATE TABLE语句 使用PARTITION BY HASHHashes one or more columns to create a key for placing and locating rows.expris an expression using one or more table columns. This can be any valid MySQL expression (including MySQL functions) that yields a single integer value. For example, these are both validCREATE TABLEstatements usingPARTITION BY HASH:CREATE TABLE t1 (col1 INT, col2 CHAR(5)) PARTITION BY HASH(col1); CREATE TABLE t1 (col1 INT, col2 CHAR(5), col3 DATETIME) PARTITION BY HASH ( YEAR(col3) );你不能在子句中使用
VALUES LESS THANTHAN 或VALUES IN子句,PARTITION BY HASHYou may not use eitherVALUES LESS THANorVALUES INclauses withPARTITION BY HASH.PARTITION BY HASH使用expr除以分区数(即模数)的剩余部分。有关示例和更多信息,请参见 第 26.2.4 节,“HASH Partitioning”。PARTITION BY HASHuses the remainder ofexprdivided by the number of partitions (that is, the modulus). For examples and additional information, see Section 26.2.4, “HASH Partitioning”.LINEAR关键字涉及一种略有不同的算法。在这种情况下,存储某一行的分区号是通过一个或多个逻辑AND运算的结果计算得到的。有关线性哈希的讨论和示例,请参见 第 26.2.4.1 节,“LINEAR HASH 分区”。TheLINEARkeyword entails a somewhat different algorithm. In this case, the number of the partition in which a row is stored is calculated as the result of one or more logicalANDoperations. For discussion and examples of linear hashing, see Section 26.2.4.1, “LINEAR HASH Partitioning”.KEY(column_list)这类似于
HASH,但 MySQL 提供哈希函数以保证数据均匀分布。column_list参数只是一个或多个表列的列表(最多 16 列)。此示例显示一个通过键分区的简单表,共有 4 个分区:This is similar toHASH, except that MySQL supplies the hashing function so as to guarantee an even data distribution. Thecolumn_listargument is simply a list of 1 or more table columns (maximum: 16). This example shows a simple table partitioned by key, with 4 partitions:CREATE TABLE tk (col1 INT, col2 CHAR(5), col3 DATE) PARTITION BY KEY(col3) PARTITIONS 4;对于通过键分区的表,可以使用
LINEAR关键字采用线性分区。这对通过HASH分区的表具有相同效果。也就是说,分区号是使用&运算符,而不是模运算来找到(参见 第 26.2.4.1 节,“LINEAR HASH 分区” 和 第 26.2.5 节,“KEY 分区”,了解详情)。此示例使用键的线性分区将数据分布到 5 个分区:For tables that are partitioned by key, you can employ linear partitioning by using theLINEARkeyword. This has the same effect as with tables that are partitioned byHASH. That is, the partition number is found using the&operator rather than the modulus (see Section 26.2.4.1, “LINEAR HASH Partitioning”, and Section 26.2.5, “KEY Partitioning”, for details). This example uses linear partitioning by key to distribute data between 5 partitions:CREATE TABLE tk (col1 INT, col2 CHAR(5), col3 DATE) PARTITION BY LINEAR KEY(col3) PARTITIONS 5;ALGORITHM={1 | 2}选项在[SUB]PARTITION BY [LINEAR] KEY中受支持。ALGORITHM=1使服务器使用与 MySQL 5.1 相同的键哈希函数;ALGORITHM=2表示服务器使用 MySQL 5.5 及以后的版本中新建KEY分区表默认实现并使用的键哈希函数。(使用 MySQL 5.5 及以后版本键哈希函数创建的分区表无法被 MySQL 5.1 服务器使用。)若未指定此选项,则效果与使用ALGORITHM=2相同。该选项主要用于在 MySQL 5.1 与之后的 MySQL 版本之间升级或降级[LINEAR] KEY分区表,或在 MySQL 5.5 或更高版本服务器上创建可被 MySQL 5.1 服务器使用的KEY或LINEAR KEY分区表。更多信息,请参见 第 15.1.9.1 节,“ALTER TABLE 分区操作”。TheALGORITHM={1 | 2}option is supported with[SUB]PARTITION BY [LINEAR] KEY.ALGORITHM=1causes the server to use the same key-hashing functions as MySQL 5.1;ALGORITHM=2means that the server employs the key-hashing functions implemented and used by default for newKEYpartitioned tables in MySQL 5.5 and later. (Partitioned tables created with the key-hashing functions employed in MySQL 5.5 and later cannot be used by a MySQL 5.1 server.) Not specifying the option has the same effect as usingALGORITHM=2. This option is intended for use chiefly when upgrading or downgrading[LINEAR] KEYpartitioned tables between MySQL 5.1 and later MySQL versions, or for creating tables partitioned byKEYorLINEAR KEYon a MySQL 5.5 or later server which can be used on a MySQL 5.1 server. For more information, see Section 15.1.9.1, “ALTER TABLE Partition Operations”.mysqldump 将此选项写入带版本注释的内容中。mysqldump writes this option encased in versioned comments.
ALGORITHM=1会在必要时显示在SHOW CREATE TABLE的输出中,使用版本注释的方式与 mysqldump 相同。即使在创建原始表时指定了此选项,ALGORITHM=2总是会从SHOW CREATE TABLE输出中省略。ALGORITHM=1is shown when necessary in the output ofSHOW CREATE TABLEusing versioned comments in the same manner as mysqldump.ALGORITHM=2is always omitted fromSHOW CREATE TABLEoutput, even if this option was specified when creating the original table.您不能在
VALUES LESS THAN中使用VALUES IN或PARTITION BY KEY子句。You may not use eitherVALUES LESS THANorVALUES INclauses withPARTITION BY KEY.RANGE(expr)在这种情况下,
expr使用一组VALUES LESS THAN运算符显示数值范围。使用范围分区时,必须至少使用VALUES LESS THAN定义一个分区。不能在范围分区中使用VALUES IN。In this case,exprshows a range of values using a set ofVALUES LESS THANoperators. When using range partitioning, you must define at least one partition usingVALUES LESS THAN. You cannot useVALUES INwith range partitioning.Note对于按
RANGE分区的表,VALUES LESS THAN必须与整数字面值或求值为单个整数值的表达式一起使用。在 MySQL 8.4 中,对于使用PARTITION BY RANGE COLUMNS定义的表,您可以克服此限制,具体说明将在本节后面描述。For tables partitioned byRANGE,VALUES LESS THANmust be used with either an integer literal value or an expression that evaluates to a single integer value. In MySQL 8.4, you can overcome this limitation in a table that is defined usingPARTITION BY RANGE COLUMNS, as described later in this section.假设您有一个表,您希望根据包含年份值的列进行分区,按照以下方案。Suppose that you have a table that you wish to partition on a column containing year values, according to the following scheme.
分区编号:Partition Number: 年份范围:Years Range: 0 1990 年及以前1990 and earlier 1 1991 至 1994 年1991 to 1994 2 1995 至 1998 年1995 to 1998 3 1999 至 2002 年1999 to 2002 4 2003 至 2005 年2003 to 2005 5 2006 年及以后2006 and later 实现这种分区方案的表可以通过如下所示的
CREATE TABLE语句来实现:A table implementing such a partitioning scheme can be realized by theCREATE TABLEstatement shown here:CREATE TABLE t1 ( year_col INT, some_data INT ) PARTITION BY RANGE (year_col) ( PARTITION p0 VALUES LESS THAN (1991), PARTITION p1 VALUES LESS THAN (1995), PARTITION p2 VALUES LESS THAN (1999), PARTITION p3 VALUES LESS THAN (2002), PARTITION p4 VALUES LESS THAN (2006), PARTITION p5 VALUES LESS THAN MAXVALUE );PARTITION ... VALUES LESS THAN ...语句按顺序工作。VALUES LESS THAN MAXVALUE用于指定那些大于其他指定最大值的“剩余”值。PARTITION ... VALUES LESS THAN ...statements work in a consecutive fashion.VALUES LESS THAN MAXVALUEworks to specify “leftover” values that are greater than the maximum value otherwise specified.VALUES LESS THAN子句按顺序工作,方式类似于许多编程语言(如 C、Java 和 PHP)中switch ... case块的case部分。也就是说,这些子句必须按顺序排列,使每个连续的VALUES LESS THAN中指定的上限大于前一个的上限,并且引用MAXVALUE的子句必须最后出现。VALUES LESS THANclauses work sequentially in a manner similar to that of thecaseportions of aswitch ... caseblock (as found in many programming languages such as C, Java, and PHP). That is, the clauses must be arranged in such a way that the upper limit specified in each successiveVALUES LESS THANis greater than that of the previous one, with the one referencingMAXVALUEcoming last of all in the list.RANGE COLUMNS(column_list)这种
RANGE的变体便于对使用多列范围条件的查询进行分区裁剪(即具有类似WHERE a = 1 AND b < 10或WHERE a = 1 AND b = 10 AND c < 10的条件)。它允许你通过在COLUMNS子句中使用列列表,并在每个PARTITION ... VALUES LESS THAN (value_list)分区定义子句中使用列值集合,来指定多列的值范围。(在最简单的情况下,该集合仅由单列组成。)column_list和value_list中可引用的最大列数为 16。This variant onRANGEfacilitates partition pruning for queries using range conditions on multiple columns (that is, having conditions such asWHERE a = 1 AND b < 10orWHERE a = 1 AND b = 10 AND c < 10). It enables you to specify value ranges in multiple columns by using a list of columns in theCOLUMNSclause and a set of column values in eachPARTITION ... VALUES LESS THAN (partition definition clause. (In the simplest case, this set consists of a single column.) The maximum number of columns that can be referenced in thevalue_list)column_listandvalue_listis 16.column_list中用于COLUMNS子句的列只能包含列名;列表中的每一列必须是以下 MySQL 数据类型之一:整数类型、字符串类型以及时间或日期列类型。使用BLOB、TEXT、SET、ENUM、BIT或空间数据类型的列不允许使用;使用浮点数类型的列也不允许使用。你也不能在COLUMNS子句中使用函数或算术表达式。Thecolumn_listused in theCOLUMNSclause may contain only names of columns; each column in the list must be one of the following MySQL data types: the integer types; the string types; and time or date column types. Columns usingBLOB,TEXT,SET,ENUM,BIT, or spatial data types are not permitted; columns that use floating-point number types are also not permitted. You also may not use functions or arithmetic expressions in theCOLUMNSclause.在分区定义中使用的
VALUES LESS THAN子句必须为COLUMNS()子句中出现的每一列指定一个字面值;也就是说,每个VALUES LESS THAN子句使用的值列表必须包含与COLUMNS子句中列数相同的值。如果在VALUES LESS THAN子句中使用的值数量与COLUMNS子句中的列数不匹配,将导致语句失败,并返回错误 Inconsistency in usage of column lists for partitioning...。你不能在VALUES LESS THAN中的任何值中使用NULL。除了第一列之外,可以在给定列中多次使用MAXVALUE,如下例所示:TheVALUES LESS THANclause used in a partition definition must specify a literal value for each column that appears in theCOLUMNS()clause; that is, the list of values used for eachVALUES LESS THANclause must contain the same number of values as there are columns listed in theCOLUMNSclause. An attempt to use more or fewer values in aVALUES LESS THANclause than there are in theCOLUMNSclause causes the statement to fail with the error Inconsistency in usage of column lists for partitioning.... You cannot useNULLfor any value appearing inVALUES LESS THAN. It is possible to useMAXVALUEmore than once for a given column other than the first, as shown in this example:CREATE TABLE rc ( a INT NOT NULL, b INT NOT NULL ) PARTITION BY RANGE COLUMNS(a,b) ( PARTITION p0 VALUES LESS THAN (10,5), PARTITION p1 VALUES LESS THAN (20,10), PARTITION p2 VALUES LESS THAN (50,MAXVALUE), PARTITION p3 VALUES LESS THAN (65,MAXVALUE), PARTITION p4 VALUES LESS THAN (MAXVALUE,MAXVALUE) );VALUES LESS THAN值列表中的值必须与对应列的类型完全匹配;不进行转换。例如,你不能用字符串'1'表示与使用整数类型的列匹配的值(你必须用数字1),也不能用数字1表示与使用字符串类型的列匹配的值(在这种情况下,必须使用引号字符串:'1')。Each value used in aVALUES LESS THANvalue list must match the type of the corresponding column exactly; no conversion is made. For example, you cannot use the string'1'for a value that matches a column that uses an integer type (you must use the numeral1instead), nor can you use the numeral1for a value that matches a column that uses a string type (in such a case, you must use a quoted string:'1').更多信息请参见 第 26.2.1 节,“RANGE Partitioning”,以及 第 26.4 节,“Partition Pruning”。For more information, see Section 26.2.1, “RANGE Partitioning”, and Section 26.4, “Partition Pruning”.
LIST(expr)LIST(expr)这在基于表列分配分区时非常有用,该列的值有限,如州或国家代码。在这种情况下,所有与某一州或国家相关的行都可以被分配到一个分区,或者为特定一组州或国家保留一个分区。它类似于
RANGE但只能使用VALUES IN来指定每个分区允许的值。This is useful when assigning partitions based on a table column with a restricted set of possible values, such as a state or country code. In such a case, all rows pertaining to a certain state or country can be assigned to a single partition, or a partition can be reserved for a certain set of states or countries. It is similar toRANGE, except that onlyVALUES INmay be used to specify permissible values for each partition.VALUES IN用于匹配的值列表。例如,你可以创建如下的分区方案:VALUES INis used with a list of values to be matched. For instance, you could create a partitioning scheme such as the following:CREATE TABLE client_firms ( id INT, name VARCHAR(35) ) PARTITION BY LIST (id) ( PARTITION r0 VALUES IN (1, 5, 9, 13, 17, 21), PARTITION r1 VALUES IN (2, 6, 10, 14, 18, 22), PARTITION r2 VALUES IN (3, 7, 11, 15, 19, 23), PARTITION r3 VALUES IN (4, 8, 12, 16, 20, 24) );使用列表分区时,必须至少定义一个分区,使用
VALUES IN你不能使用VALUES LESS THAN按列表进行PARTITION BY LIST。When using list partitioning, you must define at least one partition usingVALUES IN. You cannot useVALUES LESS THANwithPARTITION BY LIST.Note对于按
LIST,使用VALUES IN必须仅包含整数值。在 MySQL 8.4 中,可以通过按LIST COLUMNS,后面将在本节详细说明。For tables partitioned byLIST, the value list used withVALUES INmust consist of integer values only. In MySQL 8.4, you can overcome this limitation using partitioning byLIST COLUMNS, which is described later in this section.LIST COLUMNS(column_list)LIST COLUMNS(column_list)This variant on
LISTfacilitates partition pruning for queries using comparison conditions on multiple columns (that is, having conditions such asWHERE a = 5 AND b = 5或者WHERE a = 1 AND b = 10 AND c = 5). It enables you to specify values in multiple columns by using a list of columns in theCOLUMNSclause and a set of column values in eachPARTITION ... VALUES IN (partition definition clause.This variant onvalue_list)LISTfacilitates partition pruning for queries using comparison conditions on multiple columns (that is, having conditions such asWHERE a = 5 AND b = 5orWHERE a = 1 AND b = 10 AND c = 5). It enables you to specify values in multiple columns by using a list of columns in theCOLUMNSclause and a set of column values in eachPARTITION ... VALUES IN (partition definition clause.value_list)用列列表
LIST COLUMNS(值列表column_list)VALUES IN(与中所用列列表value_list)RANGE COLUMNS(值列表column_list)VALUES LESS THAN(,但value_list)VALUES IN子句,MAXVALUE不允许,并且您可以使用NULL.The rules governing regarding data types for the column list used inLIST COLUMNS(and the value list used incolumn_list)VALUES IN(are the same as those for the column list used invalue_list)RANGE COLUMNS(and the value list used incolumn_list)VALUES LESS THAN(, respectively, except that in thevalue_list)VALUES INclause,MAXVALUEis not permitted, and you may useNULL.在使用
PARTITION BY LIST COLUMNS时的VALUES IN值列表与在使用PARTITION BY LIST时的值列表之间有一个重要区别。当与PARTITION BY LIST COLUMNS一起使用时,VALUES IN子句中的每个元素必须是列值的 集合;每个集合中的值数量必须与COLUMNS子句中使用的列数量相同,并且这些值的数据类型必须与列的数据类型匹配(且顺序相同)。在最简单的情况下,这个集合由单个列组成。column_list中可以使用的列数以及构成value_list元素的值的最大数量为 16。There is one important difference between the list of values used forVALUES INwithPARTITION BY LIST COLUMNSas opposed to when it is used withPARTITION BY LIST. When used withPARTITION BY LIST COLUMNS, each element in theVALUES INclause must be a set of column values; the number of values in each set must be the same as the number of columns used in theCOLUMNSclause, and the data types of these values must match those of the columns (and occur in the same order). In the simplest case, the set consists of a single column. The maximum number of columns that can be used in thecolumn_listand in the elements making up thevalue_listis 16.下面的
CREATE TABLE语句定义的表提供了使用LIST COLUMNS分区的示例:The table defined by the followingCREATE TABLEstatement provides an example of a table usingLIST COLUMNSpartitioning:CREATE TABLE lc ( a INT NULL, b INT NULL ) PARTITION BY LIST COLUMNS(a,b) ( PARTITION p0 VALUES IN( (0,0), (NULL,NULL) ), PARTITION p1 VALUES IN( (0,1), (0,2), (0,3), (1,1), (1,2) ), PARTITION p2 VALUES IN( (1,0), (2,0), (2,1), (3,0), (3,1) ), PARTITION p3 VALUES IN( (1,3), (2,2), (2,3), (3,2), (3,3) ) );PARTITIONSnum可以通过
PARTITIONS子句(其中numnum为分区数量)来可选地指定分区数量。如果同时使用此子句 和 任意PARTITION子句,则num必须等于使用PARTITION子句声明的所有分区的总数。The number of partitions may optionally be specified with aPARTITIONSclause, wherenumnumis the number of partitions. If both this clause and anyPARTITIONclauses are used,nummust be equal to the total number of any partitions that are declared usingPARTITIONclauses.Note无论在创建按
RANGE或LIST分区的表时是否使用PARTITIONS子句,表定义中仍必须至少包含一个PARTITION VALUES子句(见下文)。Whether or not you use aPARTITIONSclause in creating a table that is partitioned byRANGEorLIST, you must still include at least onePARTITION VALUESclause in the table definition (see below).SUBPARTITION BY分区可以可选地划分为多个子分区。这可以通过使用可选的
SUBPARTITION BY子句来指示。子分区可以通过HASH或KEY进行。两者都可以是LINEAR。这些与前述的等效分区类型的工作方式相同。(无法按LIST或RANGE进行子分区。)A partition may optionally be divided into a number of subpartitions. This can be indicated by using the optionalSUBPARTITION BYclause. Subpartitioning may be done byHASHorKEY. Either of these may beLINEAR. These work in the same way as previously described for the equivalent partitioning types. (It is not possible to subpartition byLISTorRANGE.)子分区的数量可以使用
SUBPARTITIONS关键字后跟整数值来指示。The number of subpartitions can be indicated using theSUBPARTITIONSkeyword followed by an integer value.严格检查
PARTITIONS或SUBPARTITIONS子句中使用的值,并且该值必须遵循以下规则:Rigorous checking of the value used inPARTITIONSorSUBPARTITIONSclauses is applied and this value must adhere to the following rules:该值必须是正的非零整数。The value must be a positive, nonzero integer.
不允许有前导零。No leading zeros are permitted.
该值必须是整数字面量,不能是表达式。例如,
PARTITIONS 0.2E+01是不允许的,即使0.2E+01的计算结果是2。(Bug #15890)The value must be an integer literal, and cannot not be an expression. For example,PARTITIONS 0.2E+01is not permitted, even though0.2E+01evaluates to2. (Bug #15890)
partition_definition每个分区可以使用
partition_definition子句单独定义。构成该子句的各个部分如下:Each partition may be individually defined using apartition_definitionclause. The individual parts making up this clause are as follows:PARTITIONpartition_name指定分区的逻辑名称。Specifies a logical name for the partition.
VALUES对于范围分区,每个分区必须包含一个
VALUES LESS THAN子句;对于列表分区,每个分区必须指定一个VALUES IN子句。它用于确定哪些行将存储在此分区中。有关语法示例,请参阅 第 26 章,分区 中对分区类型的讨论。For range partitioning, each partition must include aVALUES LESS THANclause; for list partitioning, you must specify aVALUES INclause for each partition. This is used to determine which rows are to be stored in this partition. See the discussions of partitioning types in Chapter 26, Partitioning, for syntax examples.[STORAGE] ENGINEMySQL 接受
[STORAGE] ENGINE选项,可用于PARTITION或SUBPARTITION。目前,这个选项唯一的用法是将所有分区或所有子分区设置为相同的存储引擎,如果尝试在同一表中为分区或子分区设置不同的存储引擎,将会产生错误 ERROR 1469 (HY000): The mix of handlers in the partitions is not permitted in this version of MySQL。MySQL accepts a[STORAGE] ENGINEoption for bothPARTITIONandSUBPARTITION. Currently, the only way in which this option can be used is to set all partitions or all subpartitions to the same storage engine, and an attempt to set different storage engines for partitions or subpartitions in the same table raises the error ERROR 1469 (HY000): The mix of handlers in the partitions is not permitted in this version of MySQL.COMMENTCOMMENT可以使用可选的
COMMENT子句来指定描述分区的字符串。例如:An optionalCOMMENTclause may be used to specify a string that describes the partition. Example:COMMENT = 'Data for the years previous to 1999'
分区注释的最大长度为 1024 个字符。The maximum length for a partition comment is 1024 characters.
DATA DIRECTORY和INDEX DIRECTORYDATA DIRECTORYandINDEX DIRECTORYDATA DIRECTORY和INDEX DIRECTORY可用于分别指示此分区的数据和索引存储的目录。和data_dir都必须是绝对系统路径名。index_dirDATA DIRECTORYandINDEX DIRECTORYmay be used to indicate the directory where, respectively, the data and indexes for this partition are to be stored. Both theand thedata_dirmust be absolute system path names.index_dirDATA DIRECTORY子句中指定的目录必须是InnoDB所知的。有关更多信息,请参阅 使用 DATA DIRECTORY 子句。The directory specified in aDATA DIRECTORYclause must be known toInnoDB. For more information, see Using the DATA DIRECTORY Clause.您必须拥有
FILE权限才能使用DATA DIRECTORY或INDEX DIRECTORY分区选项。You must have theFILEprivilege to use theDATA DIRECTORYorINDEX DIRECTORYpartition option.示例:Example:
CREATE TABLE th (id INT, name VARCHAR(30), adate DATE) PARTITION BY LIST(YEAR(adate)) ( PARTITION p1999 VALUES IN (1995, 1999, 2003) DATA DIRECTORY = '/var/appdata/95/data' INDEX DIRECTORY = '/var/appdata/95/idx', PARTITION p2000 VALUES IN (1996, 2000, 2004) DATA DIRECTORY = '/var/appdata/96/data' INDEX DIRECTORY = '/var/appdata/96/idx', PARTITION p2001 VALUES IN (1997, 2001, 2005) DATA DIRECTORY = '/var/appdata/97/data' INDEX DIRECTORY = '/var/appdata/97/idx', PARTITION p2002 VALUES IN (1998, 2002, 2006) DATA DIRECTORY = '/var/appdata/98/data' INDEX DIRECTORY = '/var/appdata/98/idx' );DATA DIRECTORY和INDEX DIRECTORY的行为与CREATE TABLE语句中用于MyISAM表的table_option子句相同。DATA DIRECTORYandINDEX DIRECTORYbehave in the same way as in theCREATE TABLEstatement'stable_optionclause as used forMyISAMtables.每个分区可以指定一个数据目录和一个索引目录。如果未指定,数据和索引默认存储在表的数据库目录中。One data directory and one index directory may be specified per partition. If left unspecified, the data and indexes are stored by default in the table's database directory.
该
DATA DIRECTORY以及INDEX DIRECTORYoptions are ignored for creating partitioned tables ifNO_DIR_IN_CREATEis in effect.TheDATA DIRECTORYandINDEX DIRECTORYoptions are ignored for creating partitioned tables ifNO_DIR_IN_CREATEis in effect.MAX_ROWS和MIN_ROWSMAX_ROWSandMIN_ROWS可用于分别指定分区中存储的最大和最小行数。
max_number_of_rows和min_number_of_rows的值必须为正整数。与同名的表级选项一样,这些仅作为“的表现suggestions”,不是硬性限制。May be used to specify, respectively, the maximum and minimum number of rows to be stored in the partition. The values formax_number_of_rowsandmin_number_of_rowsmust be positive integers. As with the table-level options with the same names, these act only as “suggestions” to the server and are not hard limits.TABLESPACETABLESPACE可用于指定分区的
InnoDB文件每表表空间,即指定TABLESPACE `innodb_file_per_table`。所有分区必须属于同一存储引擎。May be used to designate anInnoDBfile-per-table tablespace for the partition by specifyingTABLESPACE `innodb_file_per_table`. All partitions must belong to the same storage engine.将
InnoDB表分区配置在共享InnoDB表空间中不被支持。共享表空间包括InnoDB系统表空间和通用表空间。PlacingInnoDBtable partitions in sharedInnoDBtablespaces is not supported. Shared tablespaces include theInnoDBsystem tablespace and general tablespaces.
subpartition_definitionsubpartition_definitionThe partition definition may optionally contain one or more
subpartition_definitionclauses. Each of these consists at a minimum of theSUBPARTITION,其中namenameis an identifier for the subpartition. Except for the replacement of thePARTITIONkeyword withSUBPARTITION, the syntax for a subpartition definition is identical to that for a partition definition.The partition definition may optionally contain one or moresubpartition_definitionclauses. Each of these consists at a minimum of theSUBPARTITION, wherenamenameis an identifier for the subpartition. Except for the replacement of thePARTITIONkeyword withSUBPARTITION, the syntax for a subpartition definition is identical to that for a partition definition.子分区必须通过
HASH或KEY,且只能在RANGE或LIST分区上进行。参见 第 26.2.6 节,“子分区”。Subpartitioning must be done byHASHorKEY, and can be done only onRANGEorLISTpartitions. See Section 26.2.6, “Subpartitioning”.
按生成列进行分区Partitioning by Generated Columns
允许按生成的列进行分区。例如:Partitioning by generated columns is permitted. For example:
CREATE TABLE t1 ( s1 INT, s2 INT AS (EXP(s1)) STORED ) PARTITION BY LIST (s2) ( PARTITION p1 VALUES IN (1) );
分区将生成列视为普通列,这使得可以绕过不允许用于分区的函数的限制(参见第 26.6.3 节,“与函数相关的分区限制”)。前面的示例演示了这种技巧:EXP() 不能直接用于 PARTITION BY 子句,但可以使用 EXP() 定义的生成列。Partitioning sees a generated column as a regular column, which
enables workarounds for limitations on functions that are not
permitted for partitioning (see
Section 26.6.3, “Partitioning Limitations Relating to Functions”). The
preceding example demonstrates this technique:
EXP() cannot be used directly in
the PARTITION BY clause, but a generated column
defined using EXP() is permitted.