MySql按条件插入数据,MySQL插入语句写where条件,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条件了!

猜你喜欢

转载自blog.csdn.net/A_art_xiang/article/details/128232841
今日推荐