【MySQL】语法 insert into ... on duplicate key update

mysql特殊语法insert into .. on duplicate key update ..使用详解 阅读详情

在向 MySQL 中插入一条记录的时候,如果基于自增主键或唯一索引键来判断该记录存在的话,则更新该记录;如果不存在,则插入该记录。这就是语法 insert into … on duplicate key update 的功能。其中,基于主键还是唯一索引键的判断依据是根据表达式中的字段名称来确定的。具体见以下示例:

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to the mysql_real_connect() C API function when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values.
:
对于每一行记录来说,如果执行结果是新增了,受影响行数为 1;如果对应记录被更新了,受影响行数为 2;如果当前记录和要更新为的记录数据一致,受影响行数为 0 。如果在连接 mysql 服务时 CLIENT_FOUND_ROWS 参数是 mysql_real_connect(),上文最后一种情况的受影响行数为 1 而不是 0 。

本示例所用 MySQL 版本为 5.5.53,存储引擎为 Innodb
参考 MySQL 官网资料地址:https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

表结构

create table t (
	id int unsigned not null auto_increment,
	a_id int unsigned not null,
	b_id int unsigned not null,
	v int unsigned not null,
	primary key (id),
	unique index `uk_a_b` (a_id, b_id)
) engine = innodb default charset = utf8;

第一次插入数据(插入了一条新记录)
插入数据
基于唯一索引插入同样的数据(更新了数据且自增值 +1)
基于唯一索引插入同样的数据

【数据库】存在则更新,不存在则插入--INSERT ON DUPLICATE KEY UPDATE【MySQL】 文章目录1、需求2、实例 1、需求 向数据库插入数据,如果 根据查询条件 原来存在那么就更新数据, 根据查询条件 不存在重复的,那么就执行插入操作。 这个时候可以使用 INSERT ON DUPLICATE KEY UPDATE 语法 INSERT INTO table_name (column_name) VALUES (column_value) ON DUPLICATE KEY UPDATE... 阅读详情

相关推荐

MySQL高效数据操作:深入解析insert into ... on duplicate key update语法实战

本文深入解析MySQL中INSERT INTO ... ON DUPLICATE KEY UPDATE语法的实战应用。该语法基于唯一索引实现“存在则更新,不存在则插入”的原子操作,能有效替代传统的“先查后改”模式,提升数据操作性能与并发安全性,并简化代码逻辑。文章通过具体场景演示了其核心机制、多唯一键冲突处理、VALUES()函数使用及常见避坑指南。

weixin_29284201的博客 401

insert...on duplicate key update语法详解

一.作用和使用场景 在mysql入库时,不能出现两条数据主键一致的情况,因为在两条数据的主键一致的情况下,mysql就会判定为待插入数据在数据库中存在重复数据,也就是说判断数据是否重复是根据主键来区别的。 但是有一些场景,如日志文件解析入库,消息队列接收数据入库等情况下可能解析到或者接收到待插入的重复数据存在重复数据则更新,不存在则插入。 这时如下语句的写法就派上用场了,on dupli...

赵英超的博客 4万+

MySQL的insert into ... on duplicate key update语法详解:从原理到避坑指南

本文深入解析MySQL中INSERT ... ON DUPLICATE KEY UPDATE语法的核心原理与实战应用。从InnoDB引擎的原子操作与锁机制入手,详解其在处理唯一键冲突时的行为,特别是多唯一索引下的优先级陷阱与避坑策略。同时,文章提供了批量操作、性能优化及VALUES()函数等进阶技巧,并对比了REPLACE语句的差异,旨在帮助开发者安全高效地使用这一强大功能,确保数据一致性与高并发性能。

weixin_29309475的博客 431

MySQL的insert-on-duplicate语句详解

MySQL的insert-on-duplicate语句详解

Charge8的博客 8953

Unity Addressable资源缓存路径自定义指南:告别C盘爆满烦恼

本文详细介绍了如何自定义Unity Addressable系统的资源缓存路径,解决其默认存储在C盘导致的磁盘空间不足问题。通过配置CacheInitializationSettings并编写编辑器脚本,开发者可以将缓存迁移至项目目录,实现资源的集中管理,提升团队协作效率与开发环境一致性。

pytorch8learner的博客 475

解忧杂货铺(四):Hightec生成HEX方法+小功能开启

Hightec使用的一些常用技能

梦想技术家 2162

mysql中INSERT INTO ... ON DUPLICATE KEY UPDATE的用法,以及与REPLACE INTO 语句用法的异同

mysql中INSERT INTO ... ON DUPLICATE KEY UPDATE的用法,以及与REPLACE INTO 语句用法的异同

jkzyx123的博客 3181

Oracle GoldenGate (OGG) 实战:从安装到故障排查的完整避坑指南

本文提供了一份详尽的Oracle GoldenGate实战指南,涵盖从环境准备、核心进程配置到性能调优与故障排查的全过程。重点解析了OGG安装与部署中的常见陷阱,并分享了确保数据同步链路稳定运行的高级运维技巧与常见故障处理方法,帮助技术人员高效避坑。

weixin_29230649的博客 380

MYSQL多种插入或修改的语法特性详解(replace into/insert ignore into/insert into on duplicate key update)

 业务背景在我们平常的业务场景中,可能有很多时候,需要对库操作进行增(未存在相应数据行)或者修改(已存在相应数据行),这时候,有人就会想到不管什么语言,我先查相应的库有没有这条行数据,再根据结果进行操作,不就完事了吗(已有的数据则修改,没有的数据则新增).能想到解决方案是好的,但是这种,先查后增或改的方案,存在很大的弊端,原因如下:        1、你先查后操作,这并不是原子性的,在多个线程进行...

没有永恒的博客 1707

LWIP协议栈在STM32H7上的内存优化实战:如何用32KB RAM实现稳定千兆以太网通信

本文深入探讨了在STM32H7微控制器上,如何通过内存优化策略,在仅32KB的D2 SRAM中稳定运行LWIP协议栈以实现千兆以太网通信。文章详细分析了STM32H7的内存架构、LWIP的内存消耗瓶颈,并提供了从描述符表与PBUF池精确分配、链接脚本修改到MPU区域划分的一整套实战优化方案,旨在解决大数据量传输卡死等常见配置问题。

gg901的博客 605

《商用密码应用与安全性评估》第四章密码应用安全性评估实施要点4.1密码应用方案设计

密码应用方案设计

qq_40442137的博客 1474

MySQL:不存在则插入,存在则更新或忽略 INSERT ... ON DUPLICATE KEY UPDATE(以联合主键为例)

MySQL语法:如果数据不存在则插入,存在则更新或忽略。) MySQL语法支持如果数据不存在则插入,存在则更新或忽略。 INSERT INTO `表名`(属性1,属性2,属性3) VALUES('值1','值2','值2') ON DUPLICATE KEY UPDATE 属性3='值3'; 本文以联合主键(即就是用多个字段一起作为一张表的主键)为例,对这一语法做测试示例。 数据表项示例:其中...

旧城以西的博客 3937

VSCode+ESP-IDF开发环境搭建:从零开始创建你的第一个物联网项目(2024最新版)

本文详细介绍了如何在2024年使用VSCode和ESP-IDF搭建物联网开发环境,从零开始创建第一个物联网项目。内容包括环境准备、ESP-IDF配置、项目创建与结构解析、构建烧录步骤以及高级技巧和常见问题解决方案,帮助开发者快速上手ESP32开发。

weixin_29165725的博客 332

MySQL特殊语法insert into ... on duplicate key update ...

MySQL特殊语法insert into .. on duplicate key update ..

qq_41982570的博客 830

Cadence IC618与Spectre231安装:环境变量与License配置详解

在Linux系统中部署Virtuoso等EDA工具时,环境变量与License管理是决定工具能否顺利启动的核心环节。环境变量决定了系统如何找到工具二进制文件以及工具如何定位自身资源,而License则通过FlexLM授权机制控制工具的使用权限。理解PATH、CDS_ROOT、CDS_LIC_FILE等关键变量的作用,掌握lmgrd服务与lmstat验证方法,能显著减少安装后启动失败的概率。无论是学生初装Cadence IC618与Spectre231,还是实验室工作站需要搭建可用的模拟设计环境,理顺环境变量

weixin_29192365的博客 372

duilib 之 事件--bubbled冒泡事件应用、通用点击事件、进入离开事件、XML样式中直接添加事件

1. box 绑定点击事件 ui::Box *pSmallVideoBox = (ui::Box*)FindControl(L"rightBox"); if (pSmallVideoBox) { auto SwitchVideo = [this](ui::EventArgs* param){ m_bSecScreenIsScale = m_bMainScre...

目前打算换一个工作,有招聘windows c++方向的也欢迎联系,北京、济南 最好 973

mysql复杂的插入语句,MYSQL多种插入或修改的语法特性详解(replace into/insert ignore into/insert into on duplicate key update...

在我们平常的业务场景中,可能有很多时候,需要对库操作进行增(未存在相应数据行)或者修改(已存在相应数据行),这时候,有人就会想到不管什么语言,我先查相应的库有没有这条行数据,再根据结果进行操作,不就完事了吗(已有的数据则修改,没有的数据则新增).能想到解决方案是好的,但是这种,先查后增或改的方案,存在很大的弊端,原因如下:1、你先查后操作,这并不是原子性的,在多个线程进行操作的时候,比如线程1和线...

weixin_29223603的博客 1268

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

mysql命令:replace into 和 on duplicate key update

replace into 跟 insert 功能类似,不同点在于:replace into 首先尝试插入数据到表中,比常规的insert语句性能更加差一般用replace语句替换一条记录的所有列,。

учёба 1350

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

mysql批量insert bug_MySQL Bug insert into on duplicate key update 语法更新 text blob 大字段导致 MySQL crash...

1. 背景业务执行 SQL 导致 MySQL 进程 Crash,做故障切换后,新的主库又 Crash 了。查看 MySQL 错误日志,发现多次 Crash 时的堆栈相同,如下:Thread pointer: 0x7fb49b866000Attempting backtrace. You can use the following information to find outwhere mysql...

weixin_30051655的博客 427

replace into和insert into on duplicate key 区别

replace的用法 当不冲突时相当于insert,其余列默认值 当key冲突时,自增列更新,replace冲突列,其余列默认值 Com_replace会加1 Innodb_rows_updated会加1 Insert into …on duplicate key的用法 不冲突时相当于insert,其余列默认值 当与key冲突时,只update相应字段值。 Com_insert会加1 ...

数据管理员 1079

关于mysql 批量更新问题

版本:mysql5.7 工具:workbench 第一种:replace语法 官网描述:https://dev.mysql.com/doc/refman/5.7/en/replace.html 语法示例: replace into t1( a, b, c) values ( 1, 322, '223312' ), (2, 666, '223312' ) , ( 1, 4443, ...

u012158591的博客 502

MySQL四种方法实现merge into

exists和in都有过滤功能,他俩最大的差别就是in引导的子句只能对一个字段进行限制,比如对id字段进行限定但是如果我们想对多个字段进行限制,使用in就不合适了,例如不过很可惜,上面的语句只能再DB2上执行,SQL Server不行此时就可以使用exists 来对多个字段进行限制了。

web_15534274656的博客 4087

告别重复数据烦恼!MySQL ON DUPLICATE KEY UPDATE 优雅解决存在更新/不存在插入难题

MySQL中的ON DUPLICATE KEY UPDATE语法提供了一种高效的"存在则更新,不存在则插入"解决方案。该语法在插入数据与主键或唯一索引冲突时,自动转为执行UPDATE操作。基本语法为在INSERT语句后添加ON DUPLICATE KEY UPDATE子句,并通过VALUES()函数引用原插入值。典型应用场景包括计数器更新、配置项维护和购物车管理等。高级用法支持条件更新、多表关联和批量操作优化。相比REPLACE INTO(先删后插)和INSERT IGNORE(忽略冲突

从基础到源码解析的学习记录 4306

on duplicate mysql,MySQL使用ON DUPLICATE KEY插入/更新多行

I'm trying to do an insert that if the id already exists it updates the row instead, but I can't seem to get it to work.This is an abridged version of the insert since there are about 1400 rows that c...

weixin_39877182的博客 222

MySQL中INSERT INTO ... ON DUPLICATE KEY UPDATE浅析

INSERT INTO ... ON DUPLICATE KEY UPDATE语法,如果数据库没有数据,就会新增一条数据,如果有数据,就会根据唯一键进行更新对应的值。

wang_666_888的博客 803

【详解】insert into update语法ON DUPLICATE KEY

ON DUPLICATE KEY UPDATE 列U1=值, 列U2=值。具体ON DUPLICATE KEY UPDATE 怎么使用。INSERT INTO 表名(唯一索引列, 列2, 列3)INSERT INTO 表名(唯一索引列, 列2, 列3)列U1 和 列U2 分别为你要修改的表格内容列的对象。VALUES (值1, 值2, 值3)VALUES (值1, 值2, 值3)以上和常规的sql写入语句用法是一样的。

woyizhizaizhaoni的专栏 759
上一篇: 【gradle】用 Gradle 构建 Java 项目
下一篇: 【PHP】与命令行的交互
November's  chopin
博客等级 码龄10年 10粉丝 42原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值