#新建表
create table t_user
(
userNamevarchar(100),
gender varchar(2)
)
#帶條件插入,如果表中沒有userName='name1'的記錄,就插入,否則就不插入
insert into t_user
select 'name1','M'
from DUAL
where not exists(
select userName #這里是select 1 或者select 列名都行
from t_user
where userName='name1'
)
注意,必須是from DUAL這個虛擬表,不能是from t_user表,否則t_user表中有幾條記錄,就會插入幾條 'name1','M‘ 的記錄. 以下的sql是錯的!錯的!錯的!
insert into t_user
select 'name2','M'
from t_user
where not exists(
select userName
from t_user
where userName='name2'
)
以前一直用的SqlServer,改為mysql之后,以為基本的怎刪改查語法都一樣。卻踩了這么個大坑,花了好長時間才找到原因.