【问题标题】:Insert values in two tables using CTE使用 CTE 在两个表中插入值
【发布时间】:2019-09-06 17:19:27
【问题描述】:

我有两张桌子(table1 和 table2)。 table2 的 id 是基于 table1 上的 id 的。

当我插入 table1 时,我想获取新创建的行的 id, 并在我克隆行时将其用于 table2,但我似乎无法正确处理。

这是一个成功克隆 TABLE1 但无法克隆 TABLE2 的示例。 表 1:

 id |      date               | status |
----+-------------------------+--------+
  1 | 2019-09-05 11:51:53.692 | ACTIVE |
  2 | 2019-09-05 11:52:49.32  | ACTIVE |
 49 | 2019-09-05 11:51:53.692 | ACTIVE |
 50 | 2019-09-05 11:52:49.32  | ACTIVE |
(4 rows)

表 2:

 id | card_last_digits | card_name |   
----+------------+------------------
  1 | 4444             | card1     | 
  2 | 4444             | card2     |
(2 rows)

SQL:

WITH cloneInsert AS (
    INSERT INTO table1 (id, date, status)
    SELECT nextval('payment_sequence'), date, 'ACTIVE'
    FROM table1
  RETURNING id)
INSERT INTO table2 (id, card_last_digits, card_name)
SELECT **cloneInsert.id**, card_last_digits, card_name
FROM table2;

【问题讨论】:

    标签: postgresql insert clone common-table-expression


    【解决方案1】:

    您很接近 - 您可能想要从 cloneinsert 中选择并插入到 table2 中。这是可以提供帮助的示例代码

    create table test1(
    id integer,
    msg text
    );
    
    create table test2(
    id integer,
    msg text
    );
    
    insert into test1 values (1, 'msg1');
    insert into test1 values (2, 'msg2');
    
    with new_rows as (
       insert into test1 values (3, 'new message')
       returning *)
    insert into test2 select id, msg
    from new_rows;
    
    > select * from test1;
     id |     msg     
    ----+-------------
      1 | msg1
      2 | msg2
      3 | new message
    (3 rows)
    
    > select * from test2;
     id |     msg     
    ----+-------------
      3 | new message
    (1 row)
    

    在 test2 上进行更新:

    with cte as (
    insert into test1 values (3, 'updated message')
    returning *)
    UPDATE test2
    SET id = cte.id, msg = cte.msg
    FROM cte WHERE test2.id = cte.id;
    

    【讨论】:

    • 嗨。我明白你的意思,但是当我在 table2 中插入时,我需要 table2 的当前数据(要克隆)并且还需要使用 table1 的新 ID。这可能吗?
    • @mengmeng 您是否希望在某些条件下更新 table2 上的现有行?
    • 我会复制table2中的行,但是table2中的id应该与table1中新插入的行相同。更新要容易得多,但过去的交易取决于此,所以我只是复制
    • @mengmeng 请提供 table1/2 的示例数据和预期输出 - 听起来可行但没有数据很难遵循
    • 我更新了描述。我希望这是可以理解的。
    猜你喜欢
    • 2020-03-29
    • 1970-01-01
    • 2015-03-20
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2014-05-26
    相关资源
    最近更新 更多