According to the information in the manual relating to ON DUPLICATE KEY UPDATE
: INSERT ... ON DUPLICATE KEY UPDATE Syntax
With the ON DUPLICATE KEY UPDATE
, the mysql_affected_rows()
is 1 if the line
is inserted as a new and 2 if an existing row is updated.
As to the REPLACE
: REPLACE Syntax
When you use a command REPLACE
, mysql_affected_rows()
will return 2 if the new row replaces an old row. This is because
a line was inserted after the duplicate line was deleted.
This fact makes it easy to determine whether REPLACE
added or subsitized a
line: check if the value of affected lines is 1 (added) or 2
(replaced).
Note that unless the table uses indexes UNIQUE
or PRIMARY KEY
, use a command REPLACE
makes no sense. He
becomes equivalent to a INSERT
, because there is no index to be used
to determine whether a new line duplicates another.
It is possible that the scenario that is bold whatever is happening to him, which is why he returns the result of 2 instead of 1.
The PT-BR manual is here: Mysql Reference Manual 4.1
Difference between REPLACE
and ON DUPLICATE KEY UPDATE
REPLACE
- Try inserting the row in the table
- If it fails, delete line and insert new line
ON DUPLICATE KEY UPDATE
- Try inserting the row in the table
- If it fails, refresh the line
Completion (responding to the two new questions)
The processes executed are similar, but in the case of REPLACE
there is a "else", which is the fact that he deletes the line and then inserts. The ON DUPLICATE KEY UPDATE
is safer in that regard because it just updates the line.
That said, the safest and almost certainly fastest way to run time will be the option ON DUPLICATE KEY UPDATE
.
Do you care about translating Quotes? It is likely that not all users know English.
– fernandosavio
Yes, of course, you’re absolutely right. Edited answer.
– João Martins
@Joãomartins Would it bother you if I asked the question "if the 2 functions perform the same processes?" because it would be very interesting and would complement the subject more.
– rbz
No @Rbz, of course not :)
– João Martins
@Joãomartins I added, and it was even more of a gift! rsrs... But as you are master in the subject, I know you will answer easily! ;)
– rbz
Edited response to answer two new questions!
– João Martins