SQL查询-更新(如果存在),否则插入 [英] SQL query- Update if exists, insert otherwise
本文介绍了SQL查询-更新(如果存在),否则插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为MySQL编写一个SQL查询,以便在存在行的情况下进行更新,而在不存在的行中进行插入.
即
如果行存在...
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
如果不存在...
INSERT INTO Table1 VALUES (...)
可以在一个查询中完成吗?
解决方案
我相信您需要颠倒逻辑才能使其起作用:
插入表中-如果存在(相同的键),则对其进行更新.
这可以通过ON DUPLICATE
语句来实现,如下所示:
INSERT INTO Table1 VALUES(...)
ON DUPLICATE KEY UPDATE column=column+1
在此处中查看手册 >
I need to write an SQL query for MySQL so that a row is updated if it exists, but inserted if it does not.
i.e.
If row exists...
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
If it does not exist...
INSERT INTO Table1 VALUES (...)
Can this be done in one query?
解决方案
i believe you need to reverse your logic in order for it to work:
insert into a table - if it exists (same key) then update it.
this can be achieved by the ON DUPLICATE
statement like so:
INSERT INTO Table1 VALUES(...)
ON DUPLICATE KEY UPDATE column=column+1
check the manual here
这篇关于SQL查询-更新(如果存在),否则插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文