REPLACE

从语义上看,REPLACE 语句是 DELETE 语句和 INSERT 语句的结合,可用于简化应用程序代码。

语法图

  1. ReplaceIntoStmt ::=
  2. 'REPLACE' PriorityOpt IntoOpt TableName PartitionNameListOpt InsertValues
  3. PriorityOpt ::=
  4. ( 'LOW_PRIORITY' | 'HIGH_PRIORITY' | 'DELAYED' )?
  5. IntoOpt ::= 'INTO'?
  6. TableName ::=
  7. Identifier ( '.' Identifier )?
  8. PartitionNameListOpt ::=
  9. ( 'PARTITION' '(' Identifier ( ',' Identifier )* ')' )?
  10. InsertValues ::=
  11. '(' ( ColumnNameListOpt ')' ( ValueSym ValuesList | SelectStmt | '(' SelectStmt ')' | UnionStmt ) | SelectStmt ')' )
  12. | ValueSym ValuesList
  13. | SelectStmt
  14. | UnionStmt
  15. | 'SET' ColumnSetValue? ( ',' ColumnSetValue )*

示例

  1. CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, c1 INT NOT NULL);
  1. Query OK, 0 rows affected (0.12 sec)
  1. INSERT INTO t1 (c1) VALUES (1), (2), (3);
  1. Query OK, 3 rows affected (0.02 sec)
  2. Records: 3 Duplicates: 0 Warnings: 0
  1. SELECT * FROM t1;
  1. +----+----+
  2. | id | c1 |
  3. +----+----+
  4. | 1 | 1 |
  5. | 2 | 2 |
  6. | 3 | 3 |
  7. +----+----+
  8. 3 rows in set (0.00 sec)
  1. REPLACE INTO t1 (id, c1) VALUES(3, 99);
  1. Query OK, 2 rows affected (0.01 sec)
  1. SELECT * FROM t1;
  1. +----+----+
  2. | id | c1 |
  3. +----+----+
  4. | 1 | 1 |
  5. | 2 | 2 |
  6. | 3 | 99 |
  7. +----+----+
  8. 3 rows in set (0.00 sec)

MySQL 兼容性

REPLACE 语句与 MySQL 完全兼容。如发现任何兼容性差异,请在 GitHub 上提交 issue

另请参阅