MySQL向数据库插入insert条件判断
我们插入数据insert时经常会做判断,什么时候插入,什么时候不插入,有数据的不插入,没有数据插入等情况,为了避免每次插数据之前select查询一下,今天我找到了 一条sql语句,能够在insert时进行判断,从而进行数据的添加或不添加。
sql如下
insert into user(name,age,sex,unique_number) SELECT '张三',22,'男','11001' from DUAL where NOT EXISTS (select unique_number from user where unique_number = '11001')
下边就是测试SQL语句的图片,可以参考一下
第一次insert
第二次insert
原理没有啥,一看就明白,sql替换参数改改直接用就可以