我用的是mysql ,有这样的一条语句
insert into user(username)values('aaa')
我想判断下表里有没有 用户名为'aaa'的,只有为空的时候才插入,
请问下用一条SQL语句是怎么写的.谢谢!

解决方案 »

  1.   

    insert into user(username) select 'aaa' from user where username is not null;
      

  2.   

    不行啊,我按 yueliangdao0608 做了,它还是会插入进去的,
    不但插入了,还一口气插入了3行了
      

  3.   

    我单独拿它到dos 下执行,还是会添加上去的,不知咋的了
      

  4.   

    insert into user(username) select (case when username = 'aaa' then NULL else 'aaa' end ) username from user;
      

  5.   

    呵呵,看来一句是实现不了了。因为MYSQL的对非KEY的NULL约束是假的。所以你必须多句完成。select count(1) from user where username = 'aaa' into @cnt;
    if @cnt = 0 then
      insert into user(username) values('aaa');
    end if;
      

  6.   

    不过如果你的username是索引的话。就可以用我的这句来实现:insert into user(username) select (case when username =  'aaa ' then NULL else  'aaa ' end ) username from user;
      

  7.   

    为username建一个unique索引,使用如下SQL语句:
    insert   ignore  into   user (username) values ( 'aaa ')