如题,LIKE不同于CREATE TABLE AS 语句,它是标准CREATE TABLE语句的一个参数项,在官方文档中可以看到:
后面还有对like_options的参数值枚举:
如上图,用法很简单,即INCLUDING后面6个值或者EXCLUDING后面6个值,例如:INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING COMMENTS,这就是一种配置方式。直观起见我们依旧通过举例说明,下面通过CREATE TABLE LIKE来完成复制:
create table t_key_event_file_student_101 (like t_key_event_file_student);复制成功后再看一下表结构的DDL语句和数据:
如上图,同CREATE TABLE AS不同的是这次复制成功拷贝了所有NOT-NULL约束,并且没有拷贝表数据,这也渐渐接近了我们的需求,并且验证了一点,就是CREATE TABLE LIKE并不会复制任何数据,而CREATE TABLE AS则会复制数据。回顾一下我们的需求:
所有约束、索引和注释在复制时都应被拷贝。
序列不应拷贝,应当为每一张复制的表单独创建一个新的序列。
接下来就要通过LIKE选项的INCLUDING关键字来实现了后续需求了,官方文档中对于CREATE TABLE的like_options有几小段详细的解释:
LIKE source_table [ like_option … ]
The LIKE clause specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints.
如上所示,当使用LIKE子句做表复制时,默认会自动拷贝所有字段、字段类型以及它们的NOT-NULL约束,这也就解释了刚才为什么会成功复制NOT-NULL约束。
Default expressions for the copied column definitions will only be copied if INCLUDING DEFAULTS is specified. The default behavior is to exclude default expressions, resulting in the copied columns in the new table having null defaults.
如上所示,当指定了INCLUDING DEFAULTS时默认的列定义均会被拷贝,这么说的话由于原始表的主键是SERIAL类型,创建后id会绑定序列,那么序列是否也会被拷贝呢?测试一下:
create table t_key_event_file_student_102 (like t_key_event_file_student INCLUDING DEFAULTS);接下来看一下DDL语句:
没错,与官方的说法一致,由于序列是指定在了列定义(column definitions )上,所以当使用了INCLUDING DEFAULTS时它自然会被复制,但这与我们的需求不符,因为我们的需求是每张被复制的表都应创建一个其专属的唯一序列,所以结论就是不能用INCLUDING DEFAULTS,继续往下看:
Not-null constraints are always copied to the new table. CHECK constraints will be copied only if INCLUDING CONSTRAINTS is specified. Indexes, PRIMARY KEY, and UNIQUE constraints on the original table will be created on the new table only if the INCLUDING INDEXES clause is specified. No distinction is made between column constraints and table constraints.
如上所示,NOT-NULL约束always copied to the new table,这一点在上面也提过了,它总会被复制。CHECK约束只有在指定了INCLUDING CONSTRAINTS时才会被拷贝,这很好理解,由于我们的原始表并没有CHECK约束,所以暂不考虑。如果希望索引、主键约束和唯一约束被复制的话,那么需要指定INCLUDING INDEXES,显然这是我们需要的,因为我们的原始表指定了主键约束,还有最后一段:
Comments for the copied columns, constraints, and indexes will only be copied if INCLUDING COMMENTS is specified. The default behavior is to exclude comments, resulting in the copied columns and constraints in the new table having no comments.
如果希望复制注释,那么需要指定INCLUDING COMMENTS,很明显,这也是我们需要的。至此我们已经可以筛选出我们需要的东西了,下面通过标���看一下:
including constraints :没有CHECK约束,所以不考虑
including indexes :需要主键约束
including comments:需要注释
including defaults:不需要复制序列,所以不要