【问题标题】:How do I insert rows in Mysql if row doesn't exist with same value如果行不存在具有相同的值,如何在 Mysql 中插入行
【发布时间】:2017-03-03 13:36:41
【问题描述】:

在 mySql 中,如果特定电子邮件不存在行,我如何插入一行,我需要从数据库表中创建一千个缺失的行,我有一个包含五千封电子邮件的文件,我不知道哪一封电子邮件已经存在在表格中,哪个不在。

我尝试像这样为每一行构造一个 sql 语句,但它是无效的 sql 语法

insert into License (email) select unique 'person@gmail.com' where not exists (select 1 from License where email='person@gmail.com');

电子邮件不是表的主键,也不一定是唯一的,我只关心如果没有记录与电子邮件地址添加记录,否则不要。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您可以通过为where 设置from 子句来解决此问题:

    insert into License (email)
        select email
        from (select 'person@gmail.com' as email) t
        where not exists (select 1 from License l where l.email = t.email);
    

    但是,在一个语句中完成所有插入会更有意义:

    insert into License (email)
        select t.email
        from database_table t
        where not exists (select 1 from License l where l.email = t.email);
    

    如果您只想要其中的 1000 个,可以添加 limit 1000

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-24
      • 2015-11-14
      • 1970-01-01
      • 2013-05-18
      相关资源
      最近更新 更多