PDA

View Full Version : UPDATE and INSERT in one go?


LaundroMat
01-13-2003, 05:43 PM
Is it possible to create a query that will do an UPDATE or an INSERT depending on certain data already in the database?
Eg I'd like to record a user's vote. If this user hasn't voted already, an INSERT is called for, otherwise an UPDATE. Right now, I'm SELECTing first, checking whether the user's id is already in the votes table, and if yes, my query's an UPDATE, otherwise it's an INSERT.
This needs two hits on the DB however, and I'm someone who likes to limit the amount of DB hits as much as possible.

Dylan Leblanc
01-13-2003, 09:56 PM
You want REPLACE. http://www.mysql.com/doc/en/REPLACE.html

LaundroMat
01-15-2003, 05:15 PM
Good one, thanks!

LaundroMat
01-17-2003, 05:57 PM
Now then, I remember why I couldn't use REPLACE...

Anyway, here's the table:

id user_id cnd_id vote week
6 1 4 1 2
2 1 2 1 1
3 2 2 1 1


Suppose I want to register the vote of user (with user_id=1) of week 2. That's an UPDATE.
But, for user_id=2, I'd have to do an INSERT, as no vote has been registered for week 2 for him before...

Edit: layout a bit messed up, but you see what I mean.
Also, the reason why I can't use REPLACE is ofcourse that there's no field to set to UNIQUE... In fact, a combination should be set to UNIQUE (which is afaik impossible, right?)