mariadb 任何替代mysql左连接复制table_B内容在table_A没有重复

fdx2calv  于 7个月前  发布在  Mysql
关注(0)|答案(2)|浏览(64)

给出两个表:

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匹配以包含所有列之外,还有其他选择吗?
先谢了。

zd287kbt

zd287kbt1#

当您使用MariaDB 10.6.11时,您可以使用10.3中添加的EXCEPT clause

INSERT INTO table_A
SELECT * FROM table_B EXCEPT ALL SELECT * FROM table_A;

对于示例数据,SELECT * FROM table_A;返回:
| col1| col2|
| --|--|
| 10 | 10 |
| 15 | 15 |
| 35 | 35 |
| 45 | 45 |
| 2000 | 2000 |
| 6000 | 6000 |
这里有一个db<>fiddle

dffbzjpn

dffbzjpn2#

如果你使用的版本不支持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有重复的行,则可能发生重复插入。

相关问题