简体   繁体   English

如何使用 SQL 将 2 个表合并为一个

[英]how to join 2 tables into one with SQL

I have 2 tables, Let's name them tb1 and tb2.我有 2 个表,我们将它们命名为 tb1 和 tb2。

I want to add all items in tb1 that dose not exist in tb2 into new rows in tb2.我想将 tb1 中不存在于 tb2 中的所有项目添加到 tb2 中的新行中。 At the same time I want to update existing data in tb2 with the data in tb1, I try to understand join, merge and so on but I could not understand how doing that in SQL.同时我想用 tb1 中的数据更新 tb2 中的现有数据,我尝试理解 join、merge 等,但我不明白在 SQL 中是如何做到的。

For the question I will build this 2 tables and the result I try to achieve.对于这个问题,我将构建这 2 个表以及我试图达到的结果。

tb1:待定1:

| KEY  | col one    | col two 
+------+------------+-----------
| 1    | data one   | data one 
| 2    | data two   | change data
| 3    | data three | data three

tb2:待定2:

| KEY  | col one   | col two 
+------+-----------+-----------
|  1   | data one  | data one
|  2   | data two  | old data
|  4   | data four | some data

tb2 after SQL: SQL 之后的 tb2:

We can see we add the key 3 and we change in key 2, col 2 data我们可以看到我们添加了 key 3 并且我们更改了 key 2, col 2 数据

| KEY  | col one    | col two 
+------+------------+-----------
|  1   | data one   | data one
|  2   | data two   | change data
|  3   | data three | data three
|  4   | data four  | some data

You can generate the results you want using union all :您可以使用union all生成所需的结果:

select t1.key, t1.col1, t1.col2
from table1 t1
union all
select t2.key, t2.col1, t2.col2
from table2 t2
where not exists (select 1 from table1 t1 where t1.key = t2.key);

Actually changing table2 is more cumbersome -- and depends on the database you are using.实际上更改table2更麻烦 - 并且取决于您使用的数据库。 One method is an insert and update :一种方法是insertupdate

update table2
    set col1 = (select t1.col1 from table1 t1 where t1.key = t2.key),
        col2 = (select t1.col2 from table1 t1 where t1.key = t2.key)
    where col1 <> (select t1.col1 from table1 t1 where t1.key = t2.key) or
          col2 <> (select t1.col2 from table1 t1 where t1.key = t2.key);

insert into table2 (key, col1, col2)
    select t1.key, t2.key, t3.key
    from table1 t1
    where not exists (select 1 from table2 t2 where t2.key = t1.key);

Specific databases have many methods for simplifying this logic, including on conflict , on duplicate key update , and merge commands.特定的数据库有很多方法可以简化这个逻辑,包括on conflicton duplicate key updatemerge命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM