日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql 检查记录存在_Mysql 插入记录时检查记录是否已经存在,存在则更新,不存在则插入记录SQL...

發(fā)布時間:2025/3/11 数据库 56 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql 检查记录存在_Mysql 插入记录时检查记录是否已经存在,存在则更新,不存在则插入记录SQL... 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

我們在開發(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。