INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[(col_name [, col_name] ...)]
{ {VALUES | VALUE} (value_list) [, (value_list)] ... }
[AS row_alias[(col_alias [, col_alias] ...)]]
[ON DUPLICATE KEY UPDATE assignment_list]
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
SET assignment_list
[AS row_alias[(col_alias [, col_alias] ...)]]
[ON DUPLICATE KEY UPDATE assignment_list]
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[(col_name [, col_name] ...)]
{ SELECT ...
| TABLE table_name
| VALUES row_constructor_list
}
[ON DUPLICATE KEY UPDATE assignment_list]
value:
{expr | DEFAULT}
value_list:
value [, value] ...
row_constructor_list:
ROW(value_list)[, ROW(value_list)][, ...]
assignment:
col_name =
value
| [row_alias.]col_name
| [tbl_name.]col_name
| [row_alias.]col_alias
assignment_list:
assignment [, assignment] ...
INSERT inserts new rows into an
existing table. The INSERT
... VALUES,
INSERT ... VALUES
ROW(),以及INSERT ... SET
forms of the statement insert rows based on explicitly specified
values. The INSERT
... SELECT form inserts rows selected from another table
or tables. You can also use
INSERT ... TABLE
to insert rows from a single table.
INSERT with an ON
DUPLICATE KEY UPDATE clause enables existing rows to be
updated if a row to be inserted would cause a duplicate value in a
UNIQUE index or PRIMARY KEY.
A row alias with one or more optional column aliases can be used
with ON DUPLICATE KEY UPDATE to refer to the
row to be inserted.INSERT inserts new rows into an
existing table. The INSERT
... VALUES,
INSERT ... VALUES
ROW(), and
INSERT ... SET
forms of the statement insert rows based on explicitly specified
values. The INSERT
... SELECT form inserts rows selected from another table
or tables. You can also use
INSERT ... TABLE
to insert rows from a single table.
INSERT with an ON
DUPLICATE KEY UPDATE clause enables existing rows to be
updated if a row to be inserted would cause a duplicate value in a
UNIQUE index or PRIMARY KEY.
A row alias with one or more optional column aliases can be used
with ON DUPLICATE KEY UPDATE to refer to the
row to be inserted.
关于 INSERT ...
SELECT 和 INSERT ... ON
DUPLICATE KEY UPDATE,参见 第 15.2.7.1 节,“插入 ...SELECT 语句”,以及 第 15.2.7.2 节,“插入 ...重复键更新语句”。For additional information about
INSERT ...
SELECT and
INSERT ... ON
DUPLICATE KEY UPDATE, see
Section 15.2.7.1, “INSERT ... SELECT Statement”, and
Section 15.2.7.2, “INSERT ... ON DUPLICATE KEY UPDATE Statement”.
在 MySQL 8.4 中,DELAYED 关键字被服务器接受但忽略。关于原因,请参见 第 15.2.7.3 节,“INSERT DELAYED Statement”,In MySQL 8.4, the DELAYED keyword
is accepted but ignored by the server. For the reasons for this,
see Section 15.2.7.3, “INSERT DELAYED Statement”,
插入表需要该INSERT表的权限。如果ON DUPLICATE KEY UPDATE使用了该子句且重复键导致执行,UPDATE语句需要UPDATE该权限来更新列。对于被读取但未被修改的列,只需该SELECT权限(例如仅col_name=expr子句ON DUPLICATE KEY UPDATE值Inserting into a table requires the
INSERT privilege for the table. If
the ON DUPLICATE KEY UPDATE clause is used and
a duplicate key causes an UPDATE to
be performed instead, the statement requires the
UPDATE privilege for the columns to
be updated. For columns that are read but not modified you need
only the SELECT privilege (such as
for a column referenced only on the right hand side of an
col_name=expr
assignment in an ON DUPLICATE KEY UPDATE
clause).
在向分区表插入数据时,您可以控制哪些分区和子分区接受新行。PARTITION 子句接受一个由一个或多个分区或子分区(或两者)的名称组成的逗号分隔列表。如果给定的 INSERT 语句插入的任何行不匹配所列分区,INSERT 语句会失败并返回错误 Found a row not matching the given partition set。更多信息和示例,请参见 第 26.5 节,“分区选择”。When inserting into a partitioned table, you can control which
partitions and subpartitions accept new rows. The
PARTITION clause takes a list of the
comma-separated names of one or more partitions or subpartitions
(or both) of the table. If any of the rows to be inserted by a
given INSERT statement do not match
one of the partitions listed, the
INSERT statement fails with the
error Found a row not matching the given partition
set. For more information and examples, see
Section 26.5, “Partition Selection”.
tbl_name 是要插入行的表。为语句提供值的列按如下方式指定:tbl_name is the table into which rows
should be inserted. Specify the columns for which the statement
provides values as follows:
在表名后提供一个括号括起的逗号分隔列名列表。在此情况下,
VALUES列表、VALUES ROW()列表或SELECT语句必须为每个列提供值。对于INSERT TABLE形式,源表的列数必须与要插入的列数匹配。Provide a parenthesized list of comma-separated column names following the table name. In this case, a value for each named column must be provided by theVALUESlist,VALUES ROW()list, orSELECTstatement. For theINSERT TABLEform, the number of columns in the source table must match the number of columns to be inserted.如果未为
INSERT ... VALUES或INSERT ... SELECT指定列名列表,则表中的每一列必须由VALUES列表、SELECT语句或TABLE语句提供值。如果不知道表中列的顺序,请使用DESCRIBE tbl_name来查看。If you do not specify a list of column names forINSERT ... VALUESorINSERT ... SELECT, values for every column in the table must be provided by theVALUESlist,SELECTstatement, orTABLEstatement. If you do not know the order of the columns in the table, useDESCRIBEto find out.tbl_nameSET子句通过列名显式指明列及其要赋的值。ASETclause indicates columns explicitly by name, together with the value to assign each one.
列的值可以通过多种方式提供:Column values can be given in several ways:
如果未启用严格 SQL 模式,任何未显式指定值的列将设置为其默认值(显式或隐式)。例如,如果指定的列列表并未列出表中的所有列,则未命名的列将设置为其默认值。默认值分配请参见 第 13.6 节,“数据类型默认值”。If strict SQL mode is not enabled, any column not explicitly given a value is set to its default (explicit or implicit) value. For example, if you specify a column list that does not name all the columns in the table, unnamed columns are set to their default values. Default value assignment is described in Section 13.6, “Data Type Default Values”.
如果启用严格 SQL 模式,当
INSERT语句未为没有默认值的每一列指定显式值时,会生成错误。请参见 第 7.1.11 节,“服务器 SQL 模式”。If strict SQL mode is enabled, anINSERTstatement generates an error if it does not specify an explicit value for every column that has no default value. See Section 7.1.11, “Server SQL Modes”.如果列列表和
VALUES列表都为空,INSERT会创建一个所有列均设置为默认值的行:If both the column list and theVALUESlist are empty,INSERTcreates a row with each column set to its default value:INSERT INTO
tbl_name() VALUES();如果没有启用严格模式,MySQL 会对没有明确定义默认值的列使用隐式默认值。如果启用严格模式,则如果任何列没有默认值,就会发生错误。If strict mode is not enabled, MySQL uses the implicit default value for any column that has no explicitly defined default. If strict mode is enabled, an error occurs if any column has no default value.
使用关键字
DEFAULT,将列明确设置为其默认值。这样可以更容易写入INSERT语句,这些语句可以为除少数列外的所有列分配值,因为这样你就能避免写出不完整的VALUES列表,而该列表中没有包含表格中每一列的值。否则,你必须提供VALUES列表。Use the keywordDEFAULTto set a column explicitly to its default value. This makes it easier to writeINSERTstatements that assign values to all but a few columns, because it enables you to avoid writing an incompleteVALUESlist that does not include a value for each column in the table. Otherwise, you must provide the list of column names corresponding to each value in theVALUESlist.如果显式插入生成列,唯一允许的值是
DEFAULT有关生成列的信息,请参见 第 15.1.20.8 节,“创建 TABLE 和生成列”If a generated column is inserted into explicitly, the only permitted value isDEFAULT. For information about generated columns, see Section 15.1.20.8, “CREATE TABLE and Generated Columns”.在表达式中,你可以使用
DEFAULT(为列生成默认值col_name)col_name.In expressions, you can useDEFAULT(to produce the default value for columncol_name)col_name.expr如果表达式数据类型与列数据类型不匹配,可能会发生表达式 expr 的类型转换。给定值的转换可能导致插入不同的值,具体取决于列类型。例如,将字符串'1999.0e-2'插入INT,FLOATDECIMAL(10,6),或YEAR列插入1999,19.992119.992100,或1999。存储在INT和YEAR列为1999,因为字符串转数字只查看字符串初始部分的有效整数或年份。对于FLOAT和DECIMAL列),字符串到数字的转换视整个字符串为有效数值。Type conversion of an expressionexprthat provides a column value might occur if the expression data type does not match the column data type. Conversion of a given value can result in different inserted values depending on the column type. For example, inserting the string'1999.0e-2'into anINT,FLOAT,DECIMAL(10,6), orYEARcolumn inserts the value1999,19.9921,19.992100, or1999, respectively. The value stored in theINTandYEARcolumns is1999because the string-to-number conversion looks only at as much of the initial part of the string as may be considered a valid integer or year. For theFLOATandDECIMALcolumns, the string-to-number conversion considers the entire string a valid numeric value.一个表达式
expr可以引用之前在值列表中设置的任何列。例如,你可以这样做,因为该值用于col2引用col1,它之前已经被分配:An expressionexprcan refer to any column that was set earlier in a value list. For example, you can do this because the value forcol2refers tocol1, which has previously been assigned:INSERT INTO
tbl_name(col1,col2) VALUES(15,col1*2);但以下内容不合法,因为
col1指向col2,该值是在col1的But the following is not legal, because the value forcol1refers tocol2, which is assigned aftercol1:INSERT INTO
tbl_name(col1,col2) VALUES(col2*2,15);:对于包含
AUTO_INCREMENT值的列存在例外。由于AUTO_INCREMENT值是在其他值赋值后生成的,任何对AUTO_INCREMENT列的引用都会返回0。An exception occurs for columns that containAUTO_INCREMENTvalues. BecauseAUTO_INCREMENTvalues are generated after other value assignments, any reference to anAUTO_INCREMENTcolumn in the assignment returns a0.
INSERT 语句使用 VALUES 语法的语句可以插入多行。为此,包含多个逗号分隔的列值列表,列表用括号包住并用逗号分隔。示例:INSERT statements that use
VALUES syntax can insert multiple rows. To do
this, include multiple lists of comma-separated column values,
with lists enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name (a,b,c)
VALUES(1,2,3), (4,5,6), (7,8,9);
每个值列表必须包含每行要插入的值数量。以下语句无效,因为它包含一个包含九个值的列表,而不是三个每个三个值的列表:Each values list must contain exactly as many values as are to be inserted per row. The following statement is invalid because it contains one list of nine values, rather than three lists of three values each:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3,4,5,6,7,8,9);
VALUE 在此语境中是 VALUES。这两者都不涉及值列表的数量,也不意味着每个列表的值数。无论存在单个值列表还是多个列表,且每个列表的值数量多少,都可以使用该列表。VALUE is a synonym for
VALUES in this context. Neither implies
anything about the number of values lists, nor about the number of
values per list. Either may be used whether there is a single
values list or multiple lists, and regardless of the number of
values per list.
INSERT 语句 使用 VALUES ROW() 语法也可以插入多行。在这种情况下,每个值列表必须包含在 ROW()行构造子)中,例如:INSERT statements using
VALUES ROW()
syntax can also insert multiple rows. In this case, each value
list must be contained within a ROW() (row
constructor), like this:
INSERT INTO tbl_name (a,b,c)
VALUES ROW(1,2,3), ROW(4,5,6), ROW(7,8,9);
受影响行的 INSERT 可通过 ROW_COUNT() SQL 函数或 mysql_affected_rows() C API 函数获得。参见 第 14.15 节,“Information Functions”,以及 mysql_affected_rows()。The affected-rows value for an
INSERT can be obtained using the
ROW_COUNT() SQL function or the
mysql_affected_rows() C API
function. See Section 14.15, “Information Functions”, and
mysql_affected_rows().
如果你使用 INSERT ...
VALUES 或 INSERT ... VALUES ROW() 包含多个值列表,或 INSERT ...
SELECT 或 INSERT ... TABLE,语句返回一个信息字符串格式如下:If you use INSERT ...
VALUES or INSERT ... VALUES ROW()
with multiple value lists, or
INSERT ...
SELECT or INSERT ... TABLE, the
statement returns an information string in this format:
Records:N1Duplicates:N2Warnings:N3
如果你使用 C API,可以通过调用 mysql_info() 函数来获得信息字符串。参见 mysql_info()。If you are using the C API, the information string can be obtained
by invoking the mysql_info()
function. See mysql_info().
Records 表示语句处理的行数。(这不一定是实际插入的行数,因为 Duplicates 可能非零。)Duplicates 表示由于会重复某个已有的唯一索引值而无法插入的行数。Warnings 表示尝试插入某些有问题的列值的次数。以下任一情况都可能产生警告:Records indicates the number of rows processed
by the statement. (This is not necessarily the number of rows
actually inserted because Duplicates can be
nonzero.) Duplicates indicates the number of
rows that could not be inserted because they would duplicate some
existing unique index value. Warnings indicates
the number of attempts to insert column values that were
problematic in some way. Warnings can occur under any of the
following conditions:
插入
NULL到已声明的列NOT NULL中。对于多行INSERT语句或INSERT INTO ... SELECT语句,该列会被设置为列数据类型的隐式默认值。对于数值类型这是0,对于字符串类型是空字符串(''),对于日期和时间类型是“零”值。INSERT INTO ... SELECT语句的处理方式与多行插入相同,因为服务器不会检查来自SELECT的结果集,以确定它是否返回单行。(对于单行INSERT,当NULL插入到NOT NULL列时,不会产生警告。相反,该语句会以错误失败。)InsertingNULLinto a column that has been declaredNOT NULL. For multiple-rowINSERTstatements orINSERT INTO ... SELECTstatements, the column is set to the implicit default value for the column data type. This is0for numeric types, the empty string ('') for string types, and the “zero” value for date and time types.INSERT INTO ... SELECTstatements are handled the same way as multiple-row inserts because the server does not examine the result set from theSELECTto see whether it returns a single row. (For a single-rowINSERT, no warning occurs whenNULLis inserted into aNOT NULLcolumn. Instead, the statement fails with an error.)将数值列设置为超出列范围的值。该值会被裁剪到范围的最近端点。Setting a numeric column to a value that lies outside the column range. The value is clipped to the closest endpoint of the range.
将类似
'10.34 a'的值赋给数值列。尾随的非数字文本将被去除,剩下的数字部分插入。如果字符串值没有前导数字部分,列将被设置为0。Assigning a value such as'10.34 a'to a numeric column. The trailing nonnumeric text is stripped off and the remaining numeric part is inserted. If the string value has no leading numeric part, the column is set to0.向字符串列(
CHAR、VARCHAR、TEXT或BLOB)插入超过列最大长度的字符串。该值将被截断到列最大长度。Inserting a string into a string column (CHAR,VARCHAR,TEXT, orBLOB) that exceeds the column maximum length. The value is truncated to the column maximum length.向日期或时间列插入数据类型非法的值。该列将被设置为该类型的零值。Inserting a value into a date or time column that is illegal for the data type. The column is set to the appropriate zero value for the type.
有关涉及
AUTO_INCREMENT列值的INSERT示例,请参见 第 5.6.9 节,“使用 AUTO_INCREMENT”。ForINSERTexamples involvingAUTO_INCREMENTcolumn values, see Section 5.6.9, “Using AUTO_INCREMENT”.如果
INSERT在一个具有AUTO_INCREMENT,你可以通过使用LAST_INSERT_ID()SQL 函数,或者mysql_insert_id()C API 函数来查找该列所用值。IfINSERTinserts a row into a table that has anAUTO_INCREMENTcolumn, you can find the value used for that column by using theLAST_INSERT_ID()SQL function or themysql_insert_id()C API function.Note这两个函数的行为并不总是完全相同。关于
INSERT语句对AUTO_INCREMENT列的行为,详见 第 14.15 节“信息函数”,以及 mysql_insert_id())。These two functions do not always behave identically. The behavior ofINSERTstatements with respect toAUTO_INCREMENTcolumns is discussed further in Section 14.15, “Information Functions”, and mysql_insert_id().
INSERT 语句支持以下修饰符:The INSERT statement supports the
following modifiers:
如果你使用
LOW_PRIORITY修饰符,执行INSERT会延迟到没有其他客户端读取该表。这包括在现有客户端读取时开始读取的其他客户端,以及当INSERT LOW_PRIORITY语句等待时。因此,客户端发出INSERT LOW_PRIORITY等待非常长时间。If you use theLOW_PRIORITYmodifier, execution of theINSERTis delayed until no other clients are reading from the table. This includes other clients that began reading while existing clients are reading, and while theINSERT LOW_PRIORITYstatement is waiting. It is possible, therefore, for a client that issues anINSERT LOW_PRIORITYstatement to wait for a very long time.LOW_PRIORITY仅影响仅使用表级锁定的存储引擎(如MyISAMMEMORYMERGELOW_PRIORITYaffects only storage engines that use only table-level locking (such asMyISAM,MEMORY, andMERGE).NoteLOW_PRIORITY通常不应与MyISAM,因为这样会禁用并发插入。参见 第 10.11.3 节,“并发插入”。LOW_PRIORITYshould normally not be used withMyISAMtables because doing so disables concurrent inserts. See Section 10.11.3, “Concurrent Inserts”.如果你指定
HIGH_PRIORITY,它会覆盖--low-priority-updatesoption(如果服务器启动时是该选项)。这也会导致并发插入不被使用。参见 第 10.11.3 节,“并发插入”。If you specifyHIGH_PRIORITY, it overrides the effect of the--low-priority-updatesoption if the server was started with that option. It also causes concurrent inserts not to be used. See Section 10.11.3, “Concurrent Inserts”.HIGH_PRIORITY仅影响仅使用表级锁定的存储引擎(例如MyISAM、MEMORY,MERGEHIGH_PRIORITYaffects only storage engines that use only table-level locking (such asMyISAM,MEMORY, andMERGE).如果你使用
IGNORE修饰符,执行INSERT语句时发生的可忽略错误将被忽略。例如,如果没有IGNORE,如果有行重复了现有的UNIQUE,或PRIMARY KEYVALUE,会导致重复键错误,语句被中止。当IGNORE,该行被丢弃,不会发生错误。被忽略的错误会生成警告。If you use theIGNOREmodifier, ignorable errors that occur while executing theINSERTstatement are ignored. For example, withoutIGNORE, a row that duplicates an existingUNIQUEindex orPRIMARY KEYvalue in the table causes a duplicate-key error and the statement is aborted. WithIGNORE, the row is discarded and no error occurs. Ignored errors generate warnings instead.IGNORE对分区表中的插入操作有类似的效果,当没有找到与给定值匹配的分区时。如果没有IGNORE,此类INSERT语句会因错误而中止。当使用INSERT IGNORE时,包含未匹配值的行会静默插入失败,但匹配的行会被插入。示例参见 第 26.2.2 节,“列表分区”。IGNOREhas a similar effect on inserts into partitioned tables where no partition matching a given value is found. WithoutIGNORE, suchINSERTstatements are aborted with an error. WhenINSERT IGNOREis used, the insert operation fails silently for rows containing the unmatched value, but inserts rows that are matched. For an example, see Section 26.2.2, “LIST Partitioning”.如果不指定
IGNORE,会触发错误的数据转换会中止语句。使用IGNORE时,无效值会调整为最接近的值并插入;会产生警告,但语句不会中止。您可以使用mysql_info()C API 函数来确定实际插入到表中的行数。Data conversions that would trigger errors abort the statement ifIGNOREis not specified. WithIGNORE, invalid values are adjusted to the closest values and inserted; warnings are produced but the statement does not abort. You can determine with themysql_info()C API function how many rows were actually inserted into the table.更多信息请参见 IGNORE 对语句执行的影响。For more information, see The Effect of IGNORE on Statement Execution.
您可以使用
REPLACE替代INSERT来覆盖旧行。REPLACE在处理包含重复旧行唯一键值的新行时,相当于INSERT IGNORE的对应操作:新行会替换旧行,而不是被丢弃。参见 第 15.2.12 节,“REPLACE 语句”。You can useREPLACEinstead ofINSERTto overwrite old rows.REPLACEis the counterpart toINSERT IGNOREin the treatment of new rows that contain unique key values that duplicate old rows: The new rows replace the old rows rather than being discarded. See Section 15.2.12, “REPLACE Statement”.如果指定
ON DUPLICATE KEY UPDATE,当插入的行会在UNIQUE索引或PRIMARY KEY中引起重复值时,会对旧行执行UPDATE。每行的受影响行数值:如果行作为新行插入,则为 1;如果更新了现有行,则为 2;如果现有行设置为其当前值,则为 0。如果在连接 mysqld 时,为mysql_real_connect()C API 函数指定了CLIENT_FOUND_ROWS标志,当现有行设置为其当前值时,受影响行数值为 1(而不是 0)。参见 第 15.2.7.2 节,“INSERT ... ON DUPLICATE KEY UPDATE 语句”。If you specifyON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in aUNIQUEindex orPRIMARY KEY, anUPDATEof the old row occurs. The affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWSflag to themysql_real_connect()C API function when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values. See Section 15.2.7.2, “INSERT ... ON DUPLICATE KEY UPDATE Statement”.INSERT DELAYED在 MySQL 5.6 中被弃用,计划最终移除。在 MySQL 8.4 中,DELAYED修饰符被接受但被忽略。请使用INSERT(不使用DELAYED)。参见 第 15.2.7.3 节,“INSERT DELAYED Statement”。INSERT DELAYEDwas deprecated in MySQL 5.6, and is scheduled for eventual removal. In MySQL 8.4, theDELAYEDmodifier is accepted but ignored. UseINSERT(withoutDELAYED) instead. See Section 15.2.7.3, “INSERT DELAYED Statement”.