This is a read-only copy of the MariaDB Knowledgebase generated on 2024-11-14. For the latest, interactive version please visit https://mariadb.com/kb/.

INSERT SELECT

语法

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name [(col_name,...)]
    SELECT ...
    [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]

描述

通过INSERT ... SELECT,你可以快速从某表或某些表中获取很多数据,并将这些数据插入到tbl_name表中。例如:

INSERT INTO tbl_temp2 (fld_id)
  SELECT tbl_temp1.fld_order_id
  FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;

tbl_name可以指定为db_name.tbl_name格式(见Identifier Qualifiers)。所以,通过INSERT ... SELECT可以在不同数据库之间拷贝数据。

如果目标表中有PRIMARY KEY或UNIQUE索引,你可以使用IGNORE关键字来处理发生重复值冲突的记录。如果索引键值出现重复,之后重复的记录不会插入到表中。

可以使用REPLACE替代INSERT语句来防止因为UNIQUE索引导致的重复值冲突记录,replace语句会删除旧的记录。此时,无法使用ON DUPLICATE KEY UPDATE语句。

INSERT ... SELECT的插入目标表必须已经存在。如果是向不存在的表插入数据,可以使用CREATE TABLE ... SELECT

See Also

Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.