文章目录
- 写在前面
- 根据条件插入数据
- 1、先准备测试数据
- 2、正常的插入语句
- 3、有条件的插入语句(重点)
- 4、查看最终结果
- 总结分析
写在前面
使用MySQL的删、改、查功能时,我们都可以根据where条件来对指定数据进行操作。
插入语句如何通过where条件,来判断是否允许插入呢?
根据条件插入数据
1、先准备测试数据
2、正常的插入语句
此时表里有三条数据了:
3、有条件的插入语句(重点)
上面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
上面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的数据,此时的临时表就可以写where条件了!