[英]How to merge two SQL tables without duplicates of a single column?
如何從不同的 SQL 表導入所有值,僅導入具有非重復“b”條目的行。 因為 'b' 符號在我的表中是唯一的字符串。 兩個表都有ca。 5mio 入門。
A_Table
structure
'id', 'a', 'b', 'c', 'd'
B_Table
structure
'a', 'b', 'c'
從 B_Table 添加到 A_Table where 'A_Table.b' !found in 'B_Table.b'
例子:
一張桌子
1, "a1", "Hallo1", "c", "d"
2, "a1", "Hallo2", "c", "d"
3, "a1", "Hallo3", "c", "d"
4, "a1", "Hallo5", "c", "d"
5, "a1", "Hallo7", "c", "d"
6, "a1", "Hallo8", "c", "d"
B_表
"a2", "Hallo1", "c"
"a2", "Hallo2", "c"
"a2", "Hallo3", "c"
"a2", "Hallo4", "c"
"a2", "Hallo5", "c"
"a2", "Hallo6", "c"
"a2", "Hallo9", "c"
查詢后的A_Table
1, "a1", "Hallo1", "c", "d"
2, "a1", "Hallo2", "c", "d"
3, "a1", "Hallo3", "c", "d"
4, "a1", "Hallo5", "c", "d"
5, "a1", "Hallo7", "c", "d"
6, "a1", "Hallo8", "c", "d"
7, "a2", "Hallo4", "c", ""
8, "a2", "Hallo6", "c", ""
9, "a2", "Hallo9", "c", ""
我想你想要union all
:
insert into a_table (a, b, c, d)
select a, b, c, ''
from b_table b
where not exists (select 1 from a_table a where a.b = b.b);
如果您關心性能,則需要a_table(b)
上的索引。
這假設id
是自動分配的。
如果你只想要一個結果集,那么union all
:
select id, a, b, c, d
from b_table a
union all
select a.max_id + row_number() over (order by b.a, b.b, b.c),
b.a, b.b, b.c, ''
from b_table b cross join
(select max(id) as max_id from table_a) a
where not exists (select 1 from a_table a where a.b = b.b);
嘗試這個:
insert into A_Table (a,b,c)
(select B_Table.a, B_Table.b, B_Table.c from B_Table left join A_Table on
A_Table.b=B_Table.b where A_Table.id is null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.