Jump to content

Recommended Posts

Hi,

 

I use something like this to update some fields:

 

$result = mysql_query("update table set visit = visit+1 where ...

if mysql_affected_rows() == 0 
mysql_query("insert into ...

 

Is it possible to write such thing by replace? for example:

 

mysql_query("replace into table (id, visit) values (id, visit+1)")
or
mysql_query("replace into table (id, visit) values (id, ifnull(visit, 0) + 1)")
or
mysql_query("replace into table (id, visit) values (id, ifnull((select visit from table where id='theNumber'), 0) + 1)")

 

first 2 does not give any error but they simply put only 1.  It doesn't add 1 to the existing value.

the third gives me

You can't specify target table 'table' for update in FROM clause

 

I'm just curious about this. No reason why I wanna change to this way.

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/167660-solved-update-with-replace-possible/
Share on other sites

Replace is a non-standard MySQL extension that has nothing to do with UPDATE really.  What it's really focused on is INSERT.  It was added to allow people to bulk insert rows into a table, and giving you a tool to deal with problems caused by key violations that might otherwise cause the bulk insert to fail.  In essence what the REPLACE does is:

 

-Does primary key of INSERT == Primary key of a row?

--- If YES

------- DELETE ROW

-INSERT NEW ROW

 

So, when you are doing an UPDATE, and specifying a value to be based on the existing value, you get the behavior you've noted, which is, that the original value get "lost" because that row gets Deleted.

 

So in short, Replace really isn't meant to be a substitute for an UPDATE, and due to the nature of the checks involved, is also going to be slower than an Update.  Replace was really added to help people who want to repeatedly re-insert a base set of rows into an existing table.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.