mysql左连接的任何替代方案将table_B内容复制到table_A中而不重复

问题描述 投票:0回答:1

给定两个表:

    create table table_A (col1 int, col2 int);
    
    insert into table_A values(10,10);
    insert into table_A values(15,15);
    insert into table_A values(35,35);
    insert into table_A values(45,45);
    
    create table table_B (col1 int, col2 int);
    
    insert into table_B values(10,10);
    insert into table_B values(2000,2000);
    insert into table_B values(35,35);
    insert into table_B values(6000,6000);

我想将每行的内容从 table_B 复制到 table_A ,除非行重复。 应用 LEFT JOIN 后的正确输出是:

    select * from table_A;
    +------+------+
    | col1 | col2 |
    +------+------+
    |   10 |   10 |
    |   15 |   15 |
    |   35 |   35 |
    |   45 |   45 |
    | 2000 | 2000 |
    | 6000 | 6000 |
    +------+------+
    
     select * from table_B;
    +------+------+
    | col1 | col2 |
    +------+------+
    |   10 |   10 |
    | 2000 | 2000 |
    |   35 |   35 |
    | 6000 | 6000 |
    +------+------+

我使用的查询是:

    INSERT IGNORE INTO test_leftjoin.table_A (SELECT DISTINCT test_leftjoin.table_B.* from test_leftjoin.table_B LEFT JOIN test_leftjoin.table_A 
    ON (test_leftjoin.table_B.col1 = test_leftjoin.table_A.col1 and test_leftjoin.table_B.col2 = test_leftjoin.table_A.col2) 
    WHERE(test_leftjoin.table_A.col1 IS NULL AND test_leftjoin.table_A.col2 IS NULL));

这很简单,因为表中只有两列,但如果我必须为具有 20-30 列的表编写相同的查询,它就会变得非常复杂和庞大。

除了在此处使用 JOIN 或简化 ON 和 WHERE 匹配以包含所有列之外,还有其他选择吗?

提前致谢。

mysql left-join
1个回答
0
投票

如果您使用的版本不支持 EXCEPT 子句,我想使用相关子查询而不是 JOIN 可以使编码更简洁:

    insert table_a  
        select distinct * from table_b b 
        where not exists (select 1 from table_a a 
                        where b.col1=a.col1 and b.col2=a.col2)  ;

注意:如果没有

distinct
关键字,如果表 b 有重复行,则可能会发生重复插入。

© www.soinside.com 2019 - 2024. All rights reserved.