Mysql 如何插入新行,但如果两个值的组合已存在,则如何更新该行?
我的桌子看起来像这样Mysql 如何插入新行,但如果两个值的组合已存在,则如何更新该行?,mysql,Mysql,我的桌子看起来像这样 CREATE TABLE sample ( id int auto_increment primary key, W_ID varchar(20), TC_ID varchar(20), foo varchar(20), bar varchar(20) ); 我想在此表中插入一个新行,但如果W_ID和TC_ID的组合已经存在,我想用新值'foo'和'bar'更新该行 我知道这里有很多类似的问题,但我想不出来 做了一个样品 我使用的是5.6.11-MyS
CREATE TABLE sample
(
id int auto_increment primary key,
W_ID varchar(20),
TC_ID varchar(20),
foo varchar(20),
bar varchar(20)
);
我想在此表中插入一个新行,但如果W_ID和TC_ID的组合已经存在,我想用新值'foo'和'bar'更新该行
我知道这里有很多类似的问题,但我想不出来
做了一个样品
我使用的是5.6.11-MySQL-Apache/2.2.22(Win32)PHP/5.3.25如果在两列上添加唯一约束,您将能够使用语法。 添加唯一约束应如下所示:
alter table table_name add unique index index_name(col1, col2);
您将找到更多详细信息您可以创建W_ID和TC_ID组合的唯一键,然后按如下方式对其执行upsert:
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';
您的结果如下所示:
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
这两列本身并不是唯一的。。。只有2的组合应该是唯一的。thnx,我的反应太快了:)