简体   繁体   English

先更新,然后更新,如果行不存在(SQL)而不是先检查行是否存在?

[英]Update first then Insert if row doesn't exist (SQL) Rather than check if row exists first?

I've always used the method of checking a table to see if a row exists, and then update it with my new data or insert it if it doesn't exist, but it's got me thinking what would be wrong with simply doing an update, if no rows are affected, then do an insert statement, that could potentially speed up my script and put less load on the server. 我一直使用检查表的方法来查看某行是否存在,然后使用我的新数据对其进行更新,或者如果不存在该行,则将其插入,但这让我想到了简单地进行更新会有什么问题,如果没有受影响的行,请执行一条插入语句,这可能会加快我的脚本的速度,并减轻服务器的负载。

Anyone foresee any problems with this? 有人预见到任何问题吗?

What's wrong with REPLACE ? REPLACE有什么问题?

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. REPLACE的工作方式与INSERT完全相同,不同之处在于,如果表中的旧行与PRIMARY KEY或UNIQUE索引的新行具有相同的值,则在插入新行之前会删除该旧行。

If by "see if a row exists" you mean by primary key, you might be interested by 12.2.5.3. 如果用“查看是否存在行”来表示主键,那么您可能会对12.2.5.3感兴趣 INSERT ... ON DUPLICATE KEY UPDATE Syntax : INSERT ... ON重复键更新语法

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. 如果您指定ON DUPLICATE KEY UPDATE,并且插入一行会导致UNIQUE索引或PRIMARY KEY中的值重复,那么将执行旧行的UPDATE。 For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect: 例如,如果将列a声明为UNIQUE并包含值1,则以下两个语句具有相同的作用:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

UPDATE table SET c=c+1 WHERE a=1;

Maybe you can use this ? 也许你可以使用这个?

Compared to what you said, tt's doing exactly the other way arround : trying to insert, and if there is a DUPLICATE KEY error, it updates the line... But it allows you not to check if the line exists first. 与您所说的相比,tt的工作方式完全相反:尝试插入,并且如果出现DUPLICATE KEY错误,它将更新该行...但是它不允许您不首先检查该行是否存在。

Still, it only works by primary key / unique index ; 不过,它只能通过主键/唯一索引来工作; not with any kind of where clause. 不能与任何形式的where子句一起使用。

REPLACE语句执行相同的操作,如果不存在某行,则将其插入;如果存在,则将对其进行更新。

INSERT IGNORE在这里也很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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