【问题标题】:Insert into table when one value not exist in another table?当另一个表中不存在一个值时插入表中?
【发布时间】:2014-04-29 22:13:32
【问题描述】:

我有两张表,它们有相同的列id,但table1ids 比table2 多。现在我想在table1中找到那些ida但在table2中不存在的insert它们到table2中,并将它们的计数值设置为0。

我尝试了以下代码,但它显示syntax error, unexpected IF

if not exists(select * from table1 where table1.id = table2.id)
begin
    insert into table2 (id, count) values (table1.id, 0)
end

【问题讨论】:

    标签: mysql sql if-statement


    【解决方案1】:

    您可以使用单个 insert . . . select 语句来做到这一点:

    insert into table2(id, count)
        select id, 0
        from table1 t1
        where not exists (select 1 from table2 t2 where t2.id = t1.id);
    

    如果您在if 上遇到错误,我猜您正在使用 MySQL(if 只允许在过程/函数/触发器代码中使用)。但即使if 允许,exists 中的查询引用table2.id 并且from 子句中没有table2。所以这将是下一个错误。

    【讨论】:

      【解决方案2】:

      这里也可以使用LEFT JOIN

      insert into table2(id, count)
      select t1.id, 0
      from table1 t1 left join table2 t2
      on t1.id = t2.id
      where t2.id is null;
      

      【讨论】:

      • 我认为这是要走的路!
      【解决方案3】:

      试试这个:

      INSERT INTO table2 (id,count)
      SELECT id,0 from table1 where id NOT IN (select id from table2)
      

      【讨论】:

        猜你喜欢
        • 2013-09-11
        • 2021-11-17
        • 1970-01-01
        • 2014-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-06
        相关资源
        最近更新 更多