简体   繁体   中英

How can I insert a new row, but if the combination of 2 values already exist update the row?

my table looks like this

CREATE TABLE sample 
(
 id int auto_increment primary key, 
 W_ID varchar(20), 
 TC_ID varchar(20),
  foo varchar(20),
  bar varchar(20)
);

I want to insert a new row into this table, but if the combination of W_ID and TC_ID already exists, i want to update the row with the new values of 'foo' and 'bar'

I know there are a lot of similar questions on here, but i can't figure it out....

made a sample in sqlfiddle.com

i am using 5.6.11-MySQL - Apache/2.2.22 (Win32) PHP/5.3.25

If you add unique constraint on the two columns you'll be able to useon duplicate key update syntax. Adding an unique constrain should be something like that:

alter table table_name add unique index index_name(col1, col2);

You'll find more details here

you can create a unique key of the combination of W_ID and TC_ID then perform your upsert on it as follows:

CREATE TABLE sample 
    (
     id int auto_increment primary key, 
     W_ID varchar(20), 
     TC_ID varchar(20),
      foo varchar(20),
      bar varchar(20)
    );

alter table sample add constraint UNIQUE (W_ID, TC_ID);

INSERT INTO sample 
(W_ID, TC_ID,foo,bar)
VALUES ('1', '2','123','123');
INSERT INTO sample 
(W_ID, TC_ID,foo,bar)
VALUES ('2', '2','123','123');
INSERT INTO sample 
(W_ID, TC_ID,foo,bar)
VALUES ('3', '2','123','123');
INSERT INTO sample 
(W_ID, TC_ID,foo,bar)
VALUES ('1', '4','123','123');
INSERT INTO sample 
(W_ID, TC_ID,foo,bar)
VALUES ('2', '3','123','123');

INSERT INTO sample 
(W_ID, TC_ID,foo,bar)
VALUES ('1', '2','123','123')
ON DUPLICATE KEY UPDATE
`foo` = 'newFoo';

your results would look like:

ID  W_ID    TC_ID    FOO    BAR
1   1   2            newFoo 123
2   2   2            123    123
3   3   2            123    123
4   1   4            123    123
5   2   3            123    123

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM