mysql 检查记录存在_Mysql 插入记录时检查记录是否已经存在,存在则更新,不存在则插入记录SQL...
我們在開發(fā)數(shù)據(jù)庫相關(guān)的邏輯過程中, 經(jīng)常檢查表中是否已經(jīng)存在這樣的一條記錄, 如果存在則更新或者不做操作, 如果沒有存在記錄,則需要插入一條新的記錄。
這樣的邏輯固然可以通過兩條sql語句完成。
SELECT COUNT(*) FROM xxx WHERE ID=xxx;
if (x == 0)
INSERT INTO xxx VALUES;
else
UPDATE xxx SET ;
但是這樣操作在性能上有所損失, 代碼結(jié)構(gòu)感覺有點丑陋。
其實MySQL提供了可以在一個SQL語句中完成上述邏輯的支持。
官方文檔如下:
MySQL provides many extentions to SQL which help performance in many
common use scenarios. Among these are INSERT … SELECT, INSERT … ON
DUPLICATE KEY UPDATE, and REPLACE.
I rarely hesitate to use the above since they are so convenient and
provide real performance benefits in many situations. MySQL has other
keywords which are more dangerous, however, and should be used
sparingly. These include INSERT DELAYED, which tells MySQL that it is
not important to insert the data immediately (say, e.g., in a logging
situation). The problem with this is that under high load situations
the insert might be delayed indefinitely, causing the insert queue to
baloon. You can also give MySQL index hints about which indices to
use. MySQL gets it right most of the time and when it doesn’t it is
usually because of a bad scheme or poorly written query.
重要的就是上面提到的 :
INSERT ... SELECT
INSERT ... ON DUPLICATE KEY UPDATE
INSERT ... ON DUPLICATE REPLACE
比如想往表中插入一條數(shù)據(jù),如果表中沒有該條數(shù)據(jù)才插入,如果已經(jīng)存在該條數(shù)據(jù)就不插入。
首先,在創(chuàng)建表時,將不需要重復(fù)的字段設(shè)置為unique,然后在插入時,使用insert ignore語句。
例如:(數(shù)據(jù)庫用的是mysql5)
創(chuàng)建一張表用來存儲用戶:
create table user_info ( uid mediumint(10) unsigned NOT NULL auto_increment primary key, last_name char(20) not null, first_name char(20) not null, unique ( last_name, first_name) );
alter table anser add UNIQUE (last_name,first_name)
插入數(shù)據(jù):
insert ignore into user_info (last_name,first_name) values ('x','y');
這樣一來,如果表中已經(jīng)存在last_name=’x’且first_name=’y’的數(shù)據(jù),就不會插入,如果沒有就會插入一條新數(shù)據(jù)。
上面的是一種用法, 也可以用 INSERT …. SELECT 來實現(xiàn)。
總結(jié)
以上是生活随笔為你收集整理的mysql 检查记录存在_Mysql 插入记录时检查记录是否已经存在,存在则更新,不存在则插入记录SQL...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle binary_intege
- 下一篇: mysql数据库的三级模式_2016年计