4

Is there a way in MySQL to find out if the last REPLACE statement actually replaced any row or just performed a regular insert? LAST_INSERT_ID() doesn't seem to help, since the autoincrement counter is updated in all cases.

4

3 回答 3

4

You need to determine the affected rows count. REPLACE doesn't update rows; it inserts or deletes and then inserts.

From the MySQL manual:

The affected-rows count makes it easy to determine whether REPLACE only added a row or whether it also replaced any rows: Check whether the count is 1 (added) or greater (replaced).

Check out the manual page: MySQL REPLACE Syntax

于 2013-04-22T13:50:10.463 回答
2

REPLACE returns the count of affected rows. This can be retrieved in SQL by ROW_COUNT().

于 2013-04-22T13:49:57.357 回答
2

If you want to know which rows have been effacted, you can also write a delete trigger that writes deleted rows to a history table.

Or let the delete trigger count the rows deleted and select it at the end of the query.

delimiter $$
CREATE TRIGGER t_yourtable_d AFTER DELETE
ON yourtable 
BEGIN
  SET @int = IFNULL(@int,0)+1;
END$$

when you are done inserting just do a

SELECT @int;

And you will get the number of rows that have been replaced. Of course this only makes sense if your query inserts/replaces more that just one row, i.e.

REPLACE INTO a(ax,ay,az) 
SELECT bx, by, bz 
FROM b;
于 2013-04-22T14:04:02.227 回答