MySQL合并不同结构的表
我有两个结构不同的数据库。
表 1:
ch_code ch_def ch_weight
表 2:
address ch_code
我需要合并这两个表,因此结构将如下所示:
ch_code ch_def ch_weight address
两个表中的数量或行数不同(表 1 有更多数据)。
我应该使用merge
、union
..其他的吗?
谢谢你!
I have two databases with different structure.
Table 1:
ch_code ch_def ch_weight
Table 2:
address ch_code
I need to merge this two tables, so the structure would look like:
ch_code ch_def ch_weight address
The number or rows in two tables are different (table 1 has more data).
Should I use merge
, union
.. something else?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
下面是一个应该处理三种可能情况的解决方案:
SELECT t1.ch_code, t1。 ch_def, t1.ch_weight, '' 作为 t1 中不存在的地址(从 t2 中选择 *,其中 t2.ch_code = t1.ch_code)
UNION
SELECT t2.ch_code, ' ' as ch_def,'' as ch_weight,t2.address 来自 t2,其中不存在(从 t1 选择 *,其中 t1.ch_code = t2.ch_code)
UNION
SELECT t1.ch_code , t1.ch_def, t1.ch_weight, t2.ch.address from t1 left join t2 on t1.ch_code = t2.ch_code
一旦你获得了结果集,如果你有一个新的结果集,你可以执行 INSERT INTO用于容纳合并数据的表。
Here's a solution which should handle the three possible cases:
SELECT t1.ch_code, t1.ch_def, t1.ch_weight, '' as address from t1 where not exists (select * from t2 where t2.ch_code = t1.ch_code)
UNION
SELECT t2.ch_code, '' as ch_def, '' as ch_weight, t2.address from t2 where not exists (select * from t1 where t1.ch_code = t2.ch_code)
UNION
SELECT t1.ch_code, t1.ch_def, t1.ch_weight, t2.ch.address from t1 left join t2 on t1.ch_code = t2.ch_code
Once you've obtained that resultset then you may do your INSERT INTO if you have a new table for housing the merged data.
如果 Table2 仅包含 Table1 中包含的数据(即 Table2 中没有 Table1 中没有的数据),您应该能够执行类似的操作(假设 Table3 已设置):(
我没有方便安装 MySQL,所以你的具体语法可能会有所不同。)
如果 Table2 中的数据与 Table1 中的数据不匹配(并且你想保留该数据),则需要 FULL JOIN (如果 MySQL 不支持,则 UNION a LEFT连接和右连接)。
If Table2 only has data that's included in Table1 (i.e. there's nothing in Table2 that's not in Table1), you should be able to do something like (assuming Table3 has been setup already):
(I don't have a MySQL install handy, so your specific syntax my vary.)
If you have data in Table2 that doesn't match data in Table1 (and you want to keep that data), you'll need a FULL JOIN (if MySQL doesn't support that, UNION a LEFT JOIN and RIGHT JOIN).