[英]How to copy certain tables from one schema to another within same DB in Postgres keeping the original schema?
I want to copy only 4 tables from schema1 to schema2 within same DB in Postgres.我只想在 Postgres 的同一个数据库中将 4 个表从 schema1 复制到 schema2。 And would like to keep the tables in schema1 as well.
并希望将表也保留在 schema1 中。 Any idea how to do that in pgadmin as well as from postgres console?
知道如何在 pgadmin 和 postgres 控制台中做到这一点吗?
You can use create table ... like
您可以使用
create table ... like
create table schema2.the_table (like schema1.the_table including all);
Then insert the data from the source to the destination:然后将数据从源插入到目标:
insert into schema2.the_table
select *
from schema1.the_table;
You can use CREATE TABLE AS SELECT.您可以使用 CREATE TABLE AS SELECT。 This ways you do not need to insert.
这种方式你不需要插入。 Table will be created with data.
将使用数据创建表。
CREATE TABLE schema2.the_table
AS
SELECT * FROM schema1.the_table;
Simple syntax that works as of v12:从 v12 开始工作的简单语法:
CREATE TABLE newSchema.newTable
AS TABLE oldSchema.oldTable;
PG dump and PG restore are usually the most efficient tools. PG dump 和 PG restore 通常是最有效的工具。
From the command line:从命令行:
pg_dump --dbname=mydb --schema=my_schema --file=/Users/my/file.dump --format=c --username=user --host=myhost --port=5432
pg_restore --dbname=mydb --schema=my_schema --format=c --username=user --host=myhost --port=5432 /Users/my/file.dump --no-owner
This will loop through all tables in the old schema and recreate them with data (no constraints, indexes, etc) in the new schema.这将遍历旧模式中的所有表,并使用新模式中的数据(无约束、索引等)重新创建它们。
-- Set the search path to the target schema
SET search_path = newSchema;
-- Loop over the table names and recreate the tables
DO $$
DECLARE
table_name text;
BEGIN
FOR table_name IN
SELECT t.table_name
FROM information_schema.tables t
WHERE t.table_schema = 'public'
AND t.table_type = 'BASE TABLE'
LOOP
EXECUTE 'CREATE TABLE ' || quote_ident(table_name) || ' AS TABLE oldSchema.' || quote_ident(table_name);
END LOOP;
END $$;
This is especially useful for collapsing multiple schemas for data warehousing when you don't need all the extras attached to the tables and just want a clean copy of the intact data.当您不需要附加到表的所有额外内容而只需要完整数据的干净副本时,这对于折叠数据仓库的多个模式特别有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.