我想将同一 Postgres 数据库中的 schema1 中的 4 张表复制到 schema2,同时也想保留这些数据在 schema1 的表。请问如何在 pgadmin 和 postgres 控制台中实现呢?
你可以使用 create table ... like
命令
create table schema2.the_table (like schema1.the_table including all);
然后将数据从源插入到目标位置:
insert into schema2.the_table
select *
from schema1.the_table;
create table new_schema."new_one" (like old_schema."old_table" including all)
- Hrvoje您可以使用CREATE TABLE AS SELECT。这样您就不需要插入数据了,表将会带有数据被创建。
CREATE TABLE schema2.the_table
AS
SELECT * FROM schema1.the_table;
schema1.the_table
中的更改是否会自动更新到 schema2.the_table
中的数据? - Pedro Cavalcante从v12版本开始,可以使用简单的语法:
CREATE TABLE newSchema.newTable
AS TABLE oldSchema.oldTable;
PG dump和PG restore通常是最有效的工具。
从命令行:
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
这将循环遍历旧模式中的所有表,并在新模式中重新创建它们(没有约束、索引等)。
-- 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 $$;
当您不需要附加到表上的所有附加功能,只想要完整数据的干净副本时,这特别适用于合并多个数据仓库模式。