Domanda

I am trying to write a query to check if a record exists (based on couple of clause and not unique identifier) if such a search return records then I need to update all the found records if nothing found then I need to INSERT a record. Note that I can't use IF EXISTS because I am trying to make a query for a client side script and not a server side. So I came a cross the idea of INSERT INTO .... ON DUPLICATE KEY

Can I do this without knowing the row key identifier? So if I find a record where accountid = 17 and name = 'Mike' then update it to make the name 'Mike A' if there is no record with these 2 clause then insert a record.

This is an attempt that is giving me a syntax error

INSERT INTO test (name, accountid) VALUES ('Mike', 17)
  ON DUPLICATE KEY 
UPDATE test SET name='Mike A' WHERE name ='Mike' AND accountid = 17

Can this method handle what I am trying to do? If yes then can you please correct my syntax?

Thank you

È stato utile?

Soluzione

The only way you can get this to work is if you have a primary key or unique constraint on the fields. From the documentation:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect:

create table test (name varchar(100), accountid int);
insert into test values ('Mike', 17);
alter table test add unique (name, accountid);

insert int test (name, accountid) values ('Mike', 17)
on duplicate key update name='Mike A';

Without the unique key, it will insert a duplicate record.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top