Find out if REPLACE statement has replaced or just inserted in MySQL

后端 未结 3 1549
粉色の甜心
粉色の甜心 2020-12-11 08:39

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 t

相关标签:
3条回答
  • 2020-12-11 08:53

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

    0 讨论(0)
  • 2020-12-11 08:55

    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

    0 讨论(0)
  • 2020-12-11 09:18

    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;
    
    0 讨论(0)
提交回复
热议问题