文章目录 写在前面根据条件插入数据1、先准备测试数据2、正常的插入语句3、有条件的插入语句(重点)4、查看最终结果 总结分析 写在前面 使用Mysql的删、改、查功能时,我们都可以根据
使用Mysql的删、改、查功能时,我们都可以根据where条件来对指定数据进行操作。
插入语句如何通过where条件,来判断是否允许插入呢?
insert into `test_table` (id, content) values('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 fromtest_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 fromtest_table
where id = 4 ) limit 1
Affected rows: 1
时间: 0.018s
我们使用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文档到电脑,方便收藏和打印~
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0