You can do this with a single query (as long as you put a unique key on id_parcele
) with the following:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO map (id_parcele, json, user_id)
VALUES (:1,:2,:3)
on duplicate key update json=// etc etc
You can also use the Replace Into syntax if you simply want to replace the values each and every time:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”.
replace INTO map (id_parcele, json, user_id)
VALUES (:1,:2,:3)
Again however, you will need to have a primary key or unique index on id_parcele
.
The difference is that the replace into
syntax will simply delete the old row first, then insert whatever you have in your query values - while the on duplicate...
syntax allows you do do something like adding a counter to see how many updates have happened to that row by using the values in it already:
Assuming your original row was created with 0 in a field called parcel_updates
(and there was such a column) you could do the following:
INSERT INTO map (id_parcele, json, user_id, parcel_updates)
VALUES (:1,:2,:3,0)
on duplicate key update parcel_updates=parcel_updates+1
This would keep the original values intact, but increase the count by one in the parcel_updates
field.
Edit: Indexes
To add an index to a table that already exists, you need to run something like this (only once) before these types of commands will work:
CREATE unique INDEX parcelID ON map (id_parcele);
This will then not allow more than one row with the same value for id_parcele
. You should however make sure that you don't already have the same value in there more than once. You can also define a column as unique when creating the table (for future reference):
create table map(
id_parcele int(10) unique key,
// etc etc