【问题标题】:Inserting rows of a table along with a separate value into another table in postgresql将表的行与单独的值一起插入到 postgresql 中的另一个表中
【发布时间】:2012-06-13 07:31:19
【问题描述】:

我有两个表 - table1 和 table2

table1 有14 columns,table2 有15 columns。两个表中的first 14 columns 相同且顺序相同。我想将 table1 的某些行复制到 table2 并在第 15 列中插入时间戳。如何编写查询?

【问题讨论】:

    标签: sql postgresql jdbc insert


    【解决方案1】:
    INSERT INTO t2(c1,c2,c3)
    SELECT c1,c2, NOW() FROM t1;
    

    您可以使用 *,但这是未来问题的一个秘诀:当您更改其中一个表中的列定义时,查询将失败。

    【讨论】:

      【解决方案2】:
      insert into table2
      select *, current_timestamp
      from table1
      where table1.some_column = 'whatever' -- etc
      

      虽然很方便,但它很脆弱。为所有列命名更简洁更好:

      insert into table2 (col1, col2, col3, ..., col15, col16)
      select col1, col2, col3, ...,  col15, current_timestamp
      from table1
      where table1.coln = 'whatever' -- etc
      

      【讨论】:

      • db如何知道“current_timestamp”不是“table1”的列,因为它也包含在select语句本身中
      • @Ashwin current_timestamp 是 postgres 中的内置关键字 - 它是保留字。你可以有一个这样的列名,但你必须在使用它时总是引用它,即select "current_timestamp" ...。应大力避免使用保留字作为列名
      • 好吧..如果我想插入时间戳以外的东西,在 col16 中说一个字符串。是否可以为此编写查询。
      猜你喜欢
      • 2012-03-06
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多