CREATE TABLE AS SELECT(CTAS)

云原生数据仓库 AnalyticDB MySQL 版支持通过CREATE TABLE创建表,也支持通过CREATE TABLE AS SELECT(CTAS)将查询到的数据写入新表中。

语法

CREATE TABLE [IF NOT EXISTS] <table_name> [table_definition]
[IGNORE|REPLACE] [AS] <query_statement>
说明

该建表方式默认与CREATE TABLE一致,支持语法也相同,例如默认为表创建全索引等。

参数

参数

说明

table_name

表名。

表名以字母或下划线(_)开头,可包含字母、数字以及下划线(_),长度为1~127个字符。

支持db_name.table_name格式,区分不同数据库下相同名字的表。

IF NOT EXISTS

判断table_name指定的表是否存在,若存在,则不执行建表语句。

IGNORE

可选参数,若表中已有相同主键的记录,新记录不会被写入。

REPLACE

可选参数,若表中已有相同主键的记录,新记录将替换已有相同主键的记录。

示例

本示例根据customer表,创建一个新的表new_customercustomer表结构如下:

CREATE TABLE customer (
customer_id bigint NOT NULL COMMENT '顾客ID',
customer_name varchar NOT NULL COMMENT '顾客姓名',
phone_num bigint NOT NULL COMMENT '电话',
city_name varchar NOT NULL COMMENT '所属城市',
sex int NOT NULL COMMENT '性别',
id_number varchar NOT NULL COMMENT '身份证号码',
home_address varchar NOT NULL COMMENT '家庭住址',
office_address varchar NOT NULL COMMENT '办公地址',
age int NOT NULL COMMENT '年龄',
login_time timestamp NOT NULL COMMENT '登录时间',
PRIMARY KEY (login_time,customer_id,phone_num)
 )
DISTRIBUTED BY HASH(customer_id)
PARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m%d')) LIFECYCLE 30
COMMENT '客户信息表';                   

示例1

customer表读取所有列数据,并将数据写入新表new_customer。新表new_customer的列名称、列数据类型与customer表相同。示例语句如下:

CREATE TABLE new_customer 
AS 
SELECT * FROM customer;

示例2

customer表读取customer_idcustomer_name列的数据,并将数据写入新表new_customer。示例语句如下:

CREATE TABLE new_customer 
AS 
SELECT customer_id, customer_name 
FROM customer;

示例3

customer表读取customer_idlogin_time列的数据,并将数据写入新表new_customer。定义新表customer_idlogin_time为主键,customer_id为分布键。示例语句如下:

CREATE TABLE new_customer (
  PRIMARY KEY (customer_id,login_time)) 
  DISTRIBUTED BY HASH (customer_id)
AS 
SELECT customer_id, login_time
FROM customer;

示例4

customer表读取customer_idlogin_time列的数据,并将数据写入新表new_customer。定义新表customer_idlogin_time为主键,customer_id为分布键,重新定义login_time列类型。示例语句如下:

CREATE TABLE new_customer (
  login_time date, 
  PRIMARY KEY (customer_id,login_time)) 
  DISTRIBUTED BY HASH (customer_id)
AS 
SELECT customer_id, login_time
FROM customer;

示例5

customer表读取customer_idcustomer_namelogin_time列的数据,并将数据写入新表new_customer。定义新表倒排索引为customer_id。示例语句如下:

CREATE TABLE new_customer (
  INDEX a_idx (customer_id))
AS 
SELECT customer_id, customer_name, login_time 
FROM customer;