广告
返回顶部
首页 > 资讯 > 数据库 >MySql按条件插入数据,MySQL插入语句写where条件,MySQL在插入时做幂等
  • 624
分享到

MySql按条件插入数据,MySQL插入语句写where条件,MySQL在插入时做幂等

mysql数据库sql 2023-10-08 21:10:11 624人浏览 八月长安
摘要

文章目录 写在前面根据条件插入数据1、先准备测试数据2、正常的插入语句3、有条件的插入语句(重点)4、查看最终结果 总结分析 写在前面 使用Mysql的删、改、查功能时,我们都可以根据

文章目录

写在前面

使用Mysql的删、改、查功能时,我们都可以根据where条件来对指定数据进行操作。

插入语句如何通过where条件,来判断是否允许插入呢?

根据条件插入数据

1、先准备测试数据

在这里插入图片描述

2、正常的插入语句

insert into `test_table` (id, content)  values('3', '内容3');

此时表里有三条数据了:
在这里插入图片描述

3、有条件的插入语句(重点)

insert into `test_table` (id, content)select * from (select '4', '内容4') as tmp where not exists ( select 1 from `test_table` where id = 1 ) limit 1;

上面sql执行结果:

insert into test_table (id, content)
select * from (select ‘4’, ‘内容4’) as tmp
where not exists ( select 1 from test_table where id = 1 ) limit 1
Affected rows: 0
时间: 0.018s

insert into `test_table` (id, content)select * from (select '4', '内容4') as tmp where not exists ( select 1 from `test_table` where id = 4 ) limit 1;

上面sql执行结果:

insert into test_table (id, content)
select * from (select ‘4’, ‘内容4’) as tmp
where not exists ( select 1 from test_table where id = 4 ) limit 1
Affected rows: 1
时间: 0.018s

4、查看最终结果

在这里插入图片描述

总结分析

我们使用insert into语句做了个取巧,我们都知道insert into语句有以下用法:

-- 插入一条INSERT INTO t1(field1,field2) VALUE(v001,v002);-- 批量插入INSERT INTO t1(field1,field2) VALUES(v101,v102),(v201,v202),(v301,v302),(v401,v402);-- 指定字段INSERT INTO t2(field1,field2) SELECT col1,col2 FROM t1 WHERE ……-- 当t2、t1表结构相同时INSERT INTO t2 SELECT id, name, address FROM t1

我们这里使用第三种方式,自定义了一个临时表,临时表的数据就是我们要insert的数据,此时的临时表就可以写where条件了!

来源地址:https://blog.csdn.net/A_art_xiang/article/details/128232841

您可能感兴趣的文档:

--结束END--

本文标题: MySql按条件插入数据,MySQL插入语句写where条件,MySQL在插入时做幂等

本文链接: https://www.lsjlt.com/news/425682.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作