在表 / 环境之间复制数据
Oracle
-- Into an existing table
INSERT INTO target_tbl (id, name) SELECT id, name FROM source_tbl WHERE status = 'ACTIVE';
-- By creating a new table (CTAS)
CREATE TABLE target_tbl AS SELECT * FROM source_tbl;
-- From a remote database via a database link
INSERT INTO target_tbl SELECT * FROM source_tbl@remote_db;同一数据库内使用 INSERT ... SELECT 或 CREATE TABLE AS SELECT(CTAS)。跨环境复制推荐使用数据库链接(@remote_db)或 Data Pump。APPEND 提示通过直接路径提升速度。
PostgreSQL
-- Same database
INSERT INTO target_tbl (id, name) SELECT id, name FROM source_tbl;
CREATE TABLE target_tbl AS SELECT * FROM source_tbl;
-- Between environments (psql pipe)
-- pg_dump -t source_tbl sourcedb | psql targetdb
-- or read the remote table with postgres_fdw and INSERT同一 DB 内使用 INSERT ... SELECT / CTAS。跨服务器使用 pg_dump | psql 管道,或通过 postgres_fdw 外部表复制。
MySQL
-- Same database
INSERT INTO target_tbl (id, name) SELECT id, name FROM source_tbl;
CREATE TABLE target_tbl AS SELECT * FROM source_tbl;
-- Between servers (mysqldump pipe)
-- mysqldump sourcedb source_tbl | mysql -h targethost targetdb同一 DB 内使用 INSERT ... SELECT 或 CREATE TABLE ... AS SELECT。不同服务器之间,常见做法是将 mysqldump 输出通过管道传给 mysql 客户端。CTAS 不会复制索引和约束。
SQL Server
-- Into an existing table
INSERT INTO target_tbl (id, name) SELECT id, name FROM source_tbl;
-- By creating a new table
SELECT * INTO target_tbl FROM source_tbl;
-- Between servers: linked server
INSERT INTO target_tbl SELECT * FROM [REMOTE_SRV].shop.dbo.source_tbl;在 SQL Server 中,复制到新表使用 SELECT ... INTO(等价于 CTAS)。跨服务器使用链接服务器(四段式名称)、bcp out/in 或 SSIS。
MongoDB
// Write an aggregation result to another collection
db.source_tbl.aggregate([
{ $match: { status: "ACTIVE" } },
{ $out: "target_tbl" }
]);
// Merge into an existing collection (upsert)
db.source_tbl.aggregate([ { $merge: { into: "target_tbl", whenMatched: "merge", whenNotMatched: "insert" } } ]);$out 完全替换目标集合;$merge 与现有文档合并/插入(同一或其他 DB)。跨服务器迁移使用 mongodump | mongorestore 或 mongoexport/mongoimport。
Redis
# Move a single key to another server (deleted from the source)
MIGRATE target_host 6379 customer:1 0 5000
# To copy (without deleting): DUMP + RESTORE
DUMP customer:1 # returns the serialized value
RESTORE customer:1new 0 "<dump-data>"MIGRATE 以原子方式将键迁移到目标实例并从源中删除(使用 COPY 选项时不删除)。在同一实例内复制使用 COPY 命令(6.0+)或 DUMP+RESTORE。
Elasticsearch
# Within the same cluster
POST _reindex
{ "source": { "index": "source_tbl" }, "dest": { "index": "target_tbl" } }
# From a remote cluster (remote reindex; requires the whitelist setting)
POST _reindex
{ "source": { "remote": { "host": "http://remote:9200" }, "index": "source_tbl" },
"dest": { "index": "target_tbl" } }_reindex 在索引之间复制数据;可通过查询过滤并用脚本转换。跨集群使用 remote reindex(目标上必须定义 reindex.remote.whitelist)。大型任务通过 slices 并行处理。