创建表 AS

概要

CREATE TABLE [ IF NOT EXISTS ] table_name [ ( column_alias, ... ) ]
[ COMMENT table_comment ]
[ WITH ( property_name = expression [, ...] ) ]
AS query
[ WITH [ NO ] DATA ]

描述

创建一个包含 SELECT 查询结果的新表。使用 CREATE TABLE 创建一个空表。

可选的 IF NOT EXISTS 子句会导致如果表已存在则抑制错误。

可选的 WITH 子句可用于在新建表上设置属性。要列出所有可用的表属性,请运行以下查询

SELECT * FROM system.metadata.table_properties

示例

创建一个名为 orders_column_aliased 的新表,其中包含查询结果和给定的列名

CREATE TABLE orders_column_aliased (order_date, total_price)
AS
SELECT orderdate, totalprice
FROM orders

创建一个名为 orders_by_date 的新表,该表对 orders 进行汇总

CREATE TABLE orders_by_date
COMMENT 'Summary of orders by date'
WITH (format = 'ORC')
AS
SELECT orderdate, sum(totalprice) AS price
FROM orders
GROUP BY orderdate

如果表 orders_by_date 不存在,则创建它

CREATE TABLE IF NOT EXISTS orders_by_date AS
SELECT orderdate, sum(totalprice) AS price
FROM orders
GROUP BY orderdate

创建一个名为 empty_nation 的新表,其模式与 nation 相同,但没有数据

CREATE TABLE empty_nation AS
SELECT *
FROM nation
WITH NO DATA

另请参阅

CREATE TABLE, SELECT