mysql - 如何合并两个 SQL 表而不重复单个列?
问题描述
如何从不同的 SQL 表中导入所有值,仅导入具有非重复“b”条目的行。因为 'b' 在我的表中代表一个唯一的字符串。两张桌子都有约。5mio 条目。
A_Table
structure
'id', 'a', 'b', 'c', 'd'
B_Table
structure
'a', 'b', 'c'
从 B_Table 添加到 A_Table,其中 'A_Table.b' !在 '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);
推荐阅读
- python - Dask read_csv——在`pd.read_csv`/`pd.read_table`中发现不匹配的dtypes
- wordpress - 在 gform_pre_send_email 函数中提交表单后获取 Gravity 表单条目 ID
- r - window() 函数排除作为结束参数发送的日期,有什么解决方法吗?
- git - Git:如何在没有多个冲突解决的情况下重新设置 Squash
- python - 按主题分组并将一列字符串折叠到相应的类别中
- angular - 根据 Angular 5,6 中的路由路径隐藏元素
- oracle - 在 oracle 触发器中获取会话操作系统用户
- regex - 正则表达式匹配确切的单词,忽略包含它作为子字符串的单词?
- sql - 在查询中添加寄存器
- java - 用JAVA点击html一段文字