【问题标题】:How to insert selected rows with another column sequence?如何使用另一个列序列插入选定的行?
【发布时间】:2014-05-21 06:31:45
【问题描述】:

我必须更改数据库结构。我们有几个具有相同列的表(大部分),现在我想将其移动到一个父表的子表,然后将数据从旧的分散表移动到新的(继承的)表。

因此,这两个表(继承的cmets_temp和主cmets)具有相同的结构,但列顺序不同:

\d comments
  Column   |            Type             |                           Modifiers
------------+-----------------------------+---------------------------------------------------------------
 comment_id | bigint                      | not null default nextval('comments_comment_id_seq'::regclass)
 post_id    | bigint                      | not null
 auser_id   | bigint                      | not null
 dt         | timestamp without time zone | not null
 text       | text                        | not null
 is_deleted | smallint                    | default 0
 parent     | bigint                      | default 0
                     | default 0

\d comments_temp
   Column   |            Type             |                             Modifiers
------------+-----------------------------+--------------------------------------------------------------------
 comment_id | bigint                      | not null default nextval('comments_base_comment_id_seq'::regclass)
 auser_id   | bigint                      | not null
 dt         | timestamp without time zone | not null
 text       | text                        | not null
 is_deleted | smallint                    | default 0
 parent     | bigint                      | default 0
 post_id    | bigint                      | not null
Inherits: comments_base

由于列的另一个顺序(尽管复制表中的事实列与新表中的列匹配),插入失败。

INSERT INTO comments_temp ( SELECT * FROM comments );

所以,我在 INSERT 上有一个错误:

ERROR:  column "dt" is of type timestamp without time zone but expression is of type bigint
LINE 1: INSERT INTO comments_temp ( SELECT * FROM comments );
                                           ^
HINT:  You will need to rewrite or cast the expression.

当列顺序在PostgreSQL中不同时如何通过选择插入?我不想使用显式列名。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    在插入中指定列:

    INSERT INTO comments_temp(comment_id, auser_id, dt, text, is_deleted, parent, post_id)
    SELECT comment_id, auser_id, dt, text, is_deleted, parent, post_id FROM comments;
    

    【讨论】:

    • 对不起。可能我在您回答后进行了编辑:我不想使用显式列名。有很多表。当然这是解决方案,但我需要一个更简单的解决方案。
    • @sergzach 如果顺序不同,我认为没有办法在不指定列的情况下做到这一点。您可以使用动态 SQL 并自动生成列名,或者使用工具为您生成查询。至于第二部分,只有第一部分指定ALL列与第二部分中的表格SAME顺序的列是不必要的。
    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 2011-08-13
    • 1970-01-01
    相关资源
    最近更新 更多