【问题标题】:How create a table AS SELECT with a serial field如何使用序列字段创建表 AS SELECT
【发布时间】:2015-11-05 14:33:06
【问题描述】:

这个查询已经有效。

    CREATE TABLE source.road_nodes (
        node_id serial,
        node TEXT
    );

    -- SAVE UNIQUE NODES AND ASIGN ID
    INSERT INTO source.road_nodes (node)
    SELECT DISTINCT  node
    FROM
        (
            (SELECT DISTINCT node_begin AS node
            FROM map.rto)
                UNION
            (SELECT DISTINCT node_end AS node
            FROM map.rto)
        ) as node_pool; 

我想知道是否有一种方法可以使用

CREATE TABLE source.road_nodes AS SELECT ( ... )

不必创建表然后执行插入。

问题是如何创建序列列。

【问题讨论】:

  • 不,这是不可能的。顺便说一句:所有这些 distinct 运算符都是无用的。 UNION 已经确保您只获得不同的值。 select node_begin from map.rto union select node_end from map.rtoinsert´ statement (and you don't need the parentheses around the select statement for create table as`所需的全部)
  • 谢谢,我放括号只是为了显示串行字段的位置。但你是对的 DISTINCT 忘记了:$

标签: postgresql create-table


【解决方案1】:

您可以将表创建为选择:

create table source.road_nodes as
select (row_number() over())::int node_id, node::text
from (  
    select node_begin node from map.rto
    union
    select node_end node from map.rto
    ) sub;

并且表中的数据将如预期的那样,但列node_id 将没有默认值。

但是,您可以手动添加适当的 default 事后:

create sequence road_nodes_node_id_seq;
select setval('road_nodes_node_id_seq', 
    (select node_id from source.road_nodes order by 1 desc limit 1));
alter table source.road_nodes alter node_id set not null; -- not necessary
alter table source.road_nodes alter node_id set default 
    nextval('road_nodes_node_id_seq'::regclass);

【讨论】:

    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2011-07-10
    相关资源
    最近更新 更多