0

I'm needing to create a query that update if the some know value exists or create a register if not.

I tried some variations like this below, but I can't put it to work.

How can I do this?

Attemp:

UPDATE OR INSERT
    mytable
SET
    attribute1 = 'value1',
    attribute2 = 'value2',
    attribute3 = 'some known value'
WHERE
    attribute3 = 'some known value'
GarouDan
  • 3,743
  • 9
  • 49
  • 75

3 Answers3

1

@GarouDan your passing only for update query no insert query use below code like this.. first find is there any record with attribute3='some known value'..for that use like this..

declare xattribute text;
select attribute3 into xsttribute where attribute3 = 'some known value'
if found
UPDATE  mytable
SET
    attribute1 = 'value1',
    attribute2 = 'value2',
    attribute3 = 'some known value'
WHERE
    attribute3 = 'some known value'
else
 insert into mytable(attribute1 ,attribute3 ,attribute3 ) values (value1,value2,some known value)
Haji
  • 1,999
  • 1
  • 15
  • 21
0

Perhaps the MySQL command REPLACE is what you are looking for. An example:

replace into cars (color,crashed) values ('black',0);
mogul
  • 4,441
  • 1
  • 18
  • 22
0

You should use mysql's INSERT...ON DUPLICATE KEY UPDATE syntax:

http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

Cargo23
  • 3,064
  • 16
  • 25