繁体   English   中英

如何合并两个 SQL 表,然后将结果附加到第三个?

[英]How can I merge two SQL tables and then append the result to a third?

假设我有以下三个表:

表格1

ID NAME
 1 John

表 2

ID   ITEM
 1  apple
 2 orange
 3 banana

表3

ID NAME   ITEM
 1 Mike  mango
 2 Mike  grape

使用 SQL 将表 1 和 2 合并在一起并将结果附加到表 3 以获得以下结果(但保持 1 和 2 不变)的最有效方法是什么?

表3 操作后

ID NAME   ITEM
  1 Mike  mango
  2 Mike  grape
  3 John  apple
  4 John orange
  5 John banana

您可以将cross joinunion all

select row_number() over (order by t.name, t.item) id, t.* from (
    select t2.name, t2.item from table2 t2
    union all
    select t1.name, t3.item from table1 t1 cross join table3 t3) t

只需在 2 之间插入一个交叉连接。
但不要插入表 3 中已经存在的那些。

insert into "Table 3" (name, item) 
select t1.name, t2.item
from "Table 1" as t1
cross join "Table 2" as t2
where not exists (
  select 1
  from "Table 3" t3
  where t3.name = t1.name
    and t3.item = t2.item
);

暂无
暂无

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

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