Mysql 数据插入与更新   replace into,insert into ...  select ... from dual where not exists,ON DUPLICATE KEY

Mysql 数据插入与更新 replace into,insert into ... select ... from dual where not exists,ON DUPLICATE KEY

如题项目中遇到的实际问题

原有表结构包含联合主键 A,B

create table 'test'(
    'A' int(10) unsigned not null,
    'value' int(10) unsigned  not null,
    'B' int(10) unsigned  not null,
    primary key ('A','B')
)

在有主键的情况下使用 replace into test('A','value','B') values(xx,xx,xx)  完全没有问题,可以实现没有的时候插入 与insert into是一样的。有的情况下更新。

还有一种方式ON DUPLICATE KEY UPDATE:

insert into test(A,value,B) values('xx','cc','vv') ON DUPLICATE KEY UPDATE value = 'cc';

也可以实现不存在插入  存在更新的目的。结合CONCAT  拼接sql语句可以更加灵活的控制数据更新,写出更加复杂的更新语句。



由于某些原因需要将联合住见去掉:alter rable test drop primary key

此时如何实现不存在插入  存在更新数据呢?这是有就可以使用 insert into ...  select ... from dual where not exists这种写法了

insert into test ('A','value','B') select 'xx','cc','vv' from dual where not exists(select * from test where A='xx' and B='vv');

上面的语句查询test表是否存在  A =‘xx’和 B=‘vv’的数据,不存在就插入,存在就忽略继续执行此时我们继续写update即可:

update test set value = 'cc' where A='xx' and B='vv';

两条语句结合使用就可以达到效果了