MySQL 从一个数据库插入另一个数据库

2023-06-02数据库问题
5

本文介绍了MySQL 从一个数据库插入另一个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要将数据从一个数据库迁移到另一个数据库,两者都在同一个本地系统上.

I need to migrate data from one Database to another one, both are on the same local system.

表和列的名称不同,我不能迁移旧数据库中的所有列,所以

The tables and columns got different names and I mustn't migrate all the Columns from the old Database, so

Select * 对我不起作用.

INSERT INTO newDatabase.table1(Column1, Column2);
SELECT oldDatabase.table1(column1, column2) FROM oldDatabase.table1

但我得到的只是一个#1064 - 语法错误

我的查询中有什么错误,我该如何解决?

What is the error in my Query and How can i fix this ?

提前致谢

推荐答案

你的查询应该是这样的:

Your query should go like this:

INSERT INTO newDatabase.table1 (Column1, Column2) 
SELECT column1, column2 FROM oldDatabase.table1;

更新

由于这个答案受到的关注比我预期的还要多,我应该扩展这个答案.首先,从答案本身可能并不明显,但列不需要具有相同的名称.因此,以下也将起作用(假设列存在于各自的表中):

Since this answer is getting more attention than I even anticipated, I should expand on this answer. First of all, it might not be obvious from the answer itself, but the columns do not need to have the same name. So, following will work too (assuming that the columns exist in their respective tables):

INSERT INTO newDatabase.table1 (Column1, Column2) 
SELECT SomeOtherColumn, MoreColumns FROM oldDatabase.table1;

此外,它们甚至不需要是表中的真正列.我经常使用的转换数据的示例之一是:

Furthermore, they don't even need to be real columns in the table. One of the examples for transforming data that I use quite often is:

INSERT INTO newDatabase.users (name, city, email, username, added_by) 
SELECT CONCAT(first_name, ' ', last_name), 'Asgard', CONCAT(first_name,'@gmail.com'), CONCAT(first_name,last_name), 'Damir' FROM oldDatabase.old_users;

因此,现在可能更明显了,规则是,只要 SELECT 查询返回与 INSERT 查询所需的列数相同的列数,就可以使用它来代替 VALUES.

So, as it might be more obvious now, the rule is, as long as the SELECT query returns same number of columns that INSERT query needs, it can be used in place of VALUES.

这篇关于MySQL 从一个数据库插入另一个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12