SELECT INTO
功能描述
SELECT INTO用于根据查询结果创建一个新表,并且将查询到的数据插入到新表中。
数据并不返回给客户端,这一点和普通的SELECT不同。新表的字段具有和SELECT的输出字段相同的名字和数据类型。
注意事项
CREATE TABLE AS的作用和SELECT INTO类似,且提供了SELECT INTO所提供功能的超集。建议使用CREATE TABLE AS语法替代SELECT INTO,因为SELECT INTO不能在存储过程中使用并且SELECT INTO 字段名,不支持接收空行。
语法格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[ WITH [ RECURSIVE ] with_query [, ...] ] SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] { * | {expression [ [ AS ] output_name ]} [, ...] } INTO [ [ GLOBAL | LOCAL | VOLATILE ] { TEMPORARY | TEMP } | UNLOGGED ] [ TABLE ] new_table [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY expression [, ...] ] [ HAVING condition [, ...] ] [ WINDOW {window_name AS ( window_definition )} [, ...] ] [ { UNION | INTERSECT | EXCEPT | MINUS } [ ALL | DISTINCT ] select ] [ ORDER BY {expression [ [ ASC | DESC | USING operator ] | nlssort_expression_clause ] [ NULLS { FIRST | LAST } ]} [, ...] ] [ { [ LIMIT { count | ALL } ] [ OFFSET start [ ROW | ROWS ] ] } | { LIMIT start, { count | ALL } } ] [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ] [ {FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ]} [...] ]; |
参数说明
INTO [ [ GLOBAL | LOCAL | VOLATILE ] { TEMPORARY | TEMP } | UNLOGGED ] [ TABLE ] new_table
[ GLOBAL | LOCAL | VOLATILE ] { TEMPORARY | TEMP }指定临时表类型,具体可参考CRATE TABLE章节中GLOBAL | LOCAL | VOLATIL...相关说明。
UNLOGGED指定表为非日志表。写入非日志表中的数据不会写入到预写日志中,这样就会比普通表快很多。但是,非日志表也是不安全的,在冲突或异常关机后会被自动删截。非日志表中的内容也不会被复制到备用服务器中。在该类表中创建的索引也不会被自动记录。
new_table指定新建表的名字。
SELECT INTO的其它参数可参考SELECT的参数说明。
示例
将reason_t表中TABLE_SK小于3的值加入到新建表中。
1 2 3 4 5 6 7 8 9 10 |
CREATE TABLE reason_t ( TABLE_SK INTEGER , TABLE_ID VARCHAR(20) , TABLE_NA VARCHAR(20) ); INSERT INTO reason_t VALUES (1, 'S01', 'StudentA'),(2, 'T01', 'TeacherA'),(3, 'T02', 'TeacherB'),(3, 'S02', 'StudentB'); SELECT * INTO reason_t_bck FROM reason_t WHERE TABLE_SK < 3; INSERT 0 2 |