Search the MySQL manual:
Subscribe to the monthly
MySQL Newsletter!

6.4.8 Синтаксис оператора REPLACE

    REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name [(col_name,...)]
        VALUES (expression,...),(...),...
или REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name [(col_name,...)]
        SELECT ...
или REPLACE [LOW_PRIORITY | DELAYED]
        [INTO] tbl_name
        SET col_name=expression, col_name=expression,...

Оператор REPLACE работает точно так же, как INSERT, за исключением того, что если старая запись в данной таблице имеет то же значение индекса UNIQUE или PRIMARY KEY, что и новая, то старая запись перед занесением новой будет удалена. See section 6.4.3 Синтаксис оператора INSERT.

Другими словами, команда REPLACE не предоставляет доступа к замещаемой записи. В некоторых старых версиях MySQL такой доступ иногда оказывался возможным, но это был дефект, который уже исправлен.

Для использования REPLACE у вас должны быть привилегии INSERT и DELETE для таблицы.

При использовании команды REPLACE функция mysql_affected_rows() вернет значение, равное 2, если старая строка была заменена новой. Объясняется это тем, что в таблицу вставляется строка после того, как удаляется дубликат.

Это позволяет легко определять, какое действие произвела команда REPLACE - добавление или замещение строки. Достаточно просто проверить, какое число вернула функция mysql_affected_rows() - 1 (строка добавлена) или 2 (замещена).

Следует учитывать, что, если не используются индексы UNIQUE или PRIMARY KEY, то применение команды REPLACE не имеет смысла, так как она работает просто как INSERT.

User Comments

Posted by Mike Cepek on January 29 2004 11:43am[Delete] [Edit]

The documentation here for REPLACE isn't clear about what happens when: a value for a column in the new row isn't specified, but the old row has a value for that column. Does the new row "inherit" the value of the old row for that column? Or does the new row use the "default" value for that colums? Thus, is the "old row is deleted before the new row is inserted" description literally true? This would mean that all old values would need to be respecified in the new row, even if only one value in the old row needed to be changed. This sounds inefficient (both for the database and for the user of the database). I would recommend clarifying this page (which is my Tip :-). Seeing an authorative answer below would be cool too. Thanks.

Posted by AJ Bertenshaw on February 1 2004 4:52am[Delete] [Edit]

The REPLACE command clearly does not preserve old values under any circumstances - it deletes the old record completely.

The example situation where "only one value in the old row needed to be changed" is not very realistic, because if that's all you wanted to do, you'd perform an UPDATE command. In fact, you'd use UPDATE, if you were interested in preserving any existing data. The REPLACE command is for creating completely new records and automatically deleting old records with conflicting keys. Think of it as a variant of INSERT, not UPDATE.

Posted by Martin Schwedes on March 8 2004 7:41pm[Delete] [Edit]

"only one value in the old row needed to be changed" would be very cool, because of the fact that you can use REPLACE [...] SELECT [...] which doesn't work with UPDATE.

Add your own comment.