2014-03-13 93 views
1

我只想将不匹配的值从table2(tpl2)复制到tpl1。什么是正确的语法来做到这一点?我使用“更新内连接”,但从tpl1删除值。我应该使用插入选择吗?参见下文:用另一个更新mysql表

tpl1  tpl2    tpl1 
------ -------   ------- 
col_1  col_1   col_1 
1   1  --->  1 
2   2    2 
3   3    3 
4   4    4 
      5    5 
      6    6 
      7    7 

回答

1

你可以用insert . . . select做到这一点:

insert into tpl1(col1) 
    select col_1 
    from tpl2 
    where not exists (select 1 from tpl1 where tpl1.col_1 = tpl2.col2); 

如果你想避免重复,您也可以考虑这种方式。在tpl1(col_1)创建唯一索引或约束:

create unique index tpl1(col_1); 

然后简单地忽略已存在的任何值。使用on duplicate key update无视这种方法:

insert into tpl1(col_1) 
    select col_1 
    from tpl2 
    on duplicate key update col_1 = tpl1.col_1; 

的分配不会改变表,所以结果是重复被忽略。

+1

存在价值,我认为你的更新查询是错误的做到这一点,她(@ user3247935)不想显示输出就像你的代码,你应该看到这个帖子的输出[问题]。你的输出就像(** http://sqlfiddle.com/#!2/53a5b/1 **),她希望输出像@Bill代码(** http://sqlfiddle.com/# !2/bf3bd/1 **)... – jmail

+0

@jmail。 。 。你没有在'tbl1'上添加唯一索引。这是解决方案的重要组成部分。 (http://sqlfiddle.com/#!2/a85fe8。)这种方法与Bill的方法几乎相同*除了*它是关于被忽略的错误的具体情况。而且,我还早一分钟;)。 –

+0

我试过'没有独特的索引'..但没有用,输出中没有任何改变... – jmail

2

您可以使用INSERT IGNORE。

INSERT IGNORE INTO tpl1 SELECT * FROM tpl2; 

这意味着,当插入试图从TPL2复制一个给定的行TPL1,并且该行已经存在(即,新行会与现有的主键或唯一KEY价值冲突),那么它只是跳过那一行。

+1

+1对**简单和快速**为您的查询理解,我喜欢它@Bill – jmail

0

您可以通过左侧的接合部TPL1到TPL2,只有将那些不以TPL1

insert into tpl1 (col_1) 
    select a.col_1 
    from tpl2 a 
     left join tpl1 b using (col_1) 
    where 
     b.col_1 is null;