PostgreSql
复制表有很多选项,有些时候做完复制表的操作,发现无法将表的描述等信息复制过去,这里详细介绍一下PostgreSql
复制表的相关操作
创建测试表并写入数据
创建学生表
CREATE TABLE "public"."student" (
"student_id" int4 NOT NULL DEFAULT nextval('student_student_id_seq'::regclass),
"name" varchar(50) COLLATE "pg_catalog"."default" NOT NULL,
"age" int4 NOT NULL,
"gender" varchar(10) COLLATE "pg_catalog"."default" NOT NULL,
"address" varchar(100) COLLATE "pg_catalog"."default" NOT NULL,
"phone" varchar(20) COLLATE "pg_catalog"."default" NOT NULL,
"grade" varchar(20) COLLATE "pg_catalog"."default" NOT NULL,
CONSTRAINT "student_pkey" PRIMARY KEY ("student_id")
);
ALTER TABLE "public"."student"
OWNER TO "postgres";
COMMENT ON COLUMN "public"."student"."student_id" IS '学生id';
COMMENT ON COLUMN "public"."student"."name" IS '姓名';
COMMENT ON COLUMN "public"."student"."age" IS '年龄';
COMMENT ON COLUMN "public"."student"."gender" IS '性别';
COMMENT ON COLUMN "public"."student"."address" IS '地址';
COMMENT ON COLUMN "public"."student"."phone" IS '电话';
COMMENT ON COLUMN "public"."student"."grade" IS '年级';
写入数据
INSERT INTO student (name, age, gender, address, phone, grade) VALUES ('John Doe', 18, 'Male', 'Beijing', '1234567890', 'Grade 10');
INSERT INTO student (name, age, gender, address, phone, grade) VALUES ('Jane Smith', 19, 'Female', 'Shanghai', '0987654321', 'Grade 11');
INSERT INTO student (name, age, gender, address, phone, grade) VALUES ('Mike Johnson', 17, 'Male', 'Guangzhou', '9876543210', 'Grade 12');
复制学生表
CREATE TABLE student2 AS SELECT * FROM student;
发现问题
创建的student2表,没有字段描述信息
问题原因
使用CREATE TABLE student2 AS SELECT * FROM student
语句复制表时,不会将字段描述复制过去。这是因为字段描述是表级别的元数据,而不是数据本身的一部分。在PostgreSQL中,字段描述存储在系统目录表中,而不是在数据表中。
因此,当使用CREATE TABLE ... AS SELECT
语句复制表时,只会复制数据和字段定义,而不会复制字段描述。如果您希望复制字段描述,您需要手动为新表添加字段描述。
解决方案1
使用COMMENT
语句为新表的字段添加描述:
-- 创建student2表,复制字段定义和数据
CREATE TABLE student2 AS SELECT * FROM student;
-- 为student2表的字段添加描述
COMMENT ON COLUMN student2.student_id IS '学生id';
COMMENT ON COLUMN student2.name IS '姓名';
COMMENT ON COLUMN student2.age IS '年龄';
COMMENT ON COLUMN student2.gender IS '性别';
COMMENT ON COLUMN student2.address IS '地址';
COMMENT ON COLUMN student2.phone IS '电话';
COMMENT ON COLUMN student2.grade IS '年级';
解决方案2
CREATE TABLE ... (LIKE ...) 复制表
可以使用 CREATE TABLE ... (LIKE ...)
语句来复制表,并使用 INCLUDING
子句来指定要包括的对象,要复制表并包括索引和注释。
CREATE TABLE student3 (LIKE student INCLUDING INDEXES INCLUDING COMMENTS);
查看表详情,可以看到,已经复制了表的字段描述
INCLUDING 其它选项说明
INCLUDING ALL
:包括所有对象,相当于INCLUDING INDEXES INCLUDING CONSTRAINTS INCLUDING DEFAULTS INCLUDING STORAGE INCLUDING COMMENTS INCLUDING STATISTICS INCLUDING GENERATED INCLUDING RULES INCLUDING TRIGGERS
。INCLUDING INDEXES
:包括表的索引。INCLUDING CONSTRAINTS
:包括表的约束。INCLUDING DEFAULTS
:包括表的默认值。INCLUDING STORAGE
:包括表的存储参数。INCLUDING COMMENTS
:包括表的注释。INCLUDING STATISTICS
:包括表的统计信息。INCLUDING GENERATED
:包括表的生成列。INCLUDING RULES
:包括表的规则。INCLUDING TRIGGERS
:包括表的触发器。
你可以根据需要选择适当的 INCLUDING
选项来复制表。