【问题标题】:Insert do nothing and vice versa - 2 tables in Postgresql插入什么都不做,反之亦然 - Postgresql 中有 2 个表
【发布时间】:2020-02-06 08:59:13
【问题描述】:

我有两个如下图所示的表

Table_1

id  first_name  last_name   email
1   Artemas     Jack        asaggs0@si.edu
2   Caro        John        cstot1@businessinsider.com
3   Maire       Disha       mtilte2@answers.com
4   Cristiano   Herreros    cherreros3@xing.com
5   Mirabelle   Muschette   mmuschette4@discuz.net

Table_2

id  first_name  last_name   email
1   Artemas     Jack123     asaggs0@si.edu
2   Caro        John        cstot1@businessinsider.com
4   Cristiano   Herreros    cherreros3@xing.com
6   Arjun       Master      Arjunmas@gmail.com

几点

  1. Table_2 是最近的表(已更新数据)

  2. 我想做的是根据 Table_2 更新 Table_1 但是

    1. 不要打扰重复的行。因为没有变化(例如:table_1 中的 Id = 2,4 也存在于 table_2 中)
    2. 更新修改的行(例如:table_1 中的 Id = 1 在 table_2 中具有更新的姓氏。它可以是任何列。如果需要,我们必须查看 Id 列并更新它)
    3. 不要从 table_1 中删除 table_2 中不存在的任何行(例如:table_1 中的 Id = 3,5)

我在下面尝试了类似的方法,但没有帮助

INSERT INTO table_1 VALUES (SELECT * FROM table_2) ON CONFLICT DO NOTHING;

但不知道如何按原样保留 id = 3 & id = 5 等记录

我希望我的输出如下所示

输出

id  first_name  last_name   email
1   Artemas     Jack123     asaggs0@si.edu
2   Caro        John        cstot1@businessinsider.com
3   Maire       Disha       mtilte2@answers.com
4   Cristiano   Herreros    cherreros3@xing.com
5   Mirabelle   Muschette   mmuschette4@discuz.net
6   Arjun       Master      Arjunmas@gmail.com

【问题讨论】:

    标签: sql postgresql sql-insert


    【解决方案1】:

    您可以使用 on conflict do update 并使用 WHERE 子句仅更改发生变化的行

    INSERT INTO table_1 (id, first_name, last_name, email)
    SELECT id, first_name, last_name, email
    FROM table_2
      ON CONFLICT (id) DO UPDATE
        set first_name = excluded.first_name,
            last_name = excluded.last_name, 
            email = excluded.email
    where (table_1.first_name, table_1.last_name, table_1.email) 
             IS DISTINCT FROM (table_2.first_name, table_2.last_name, table_2.email);
    

    【讨论】:

    • 您好,感谢您的回复。赞成。我试过。一个快速但小问题
    • 我可以知道如何在不定义任何地方的情况下将别名排除在外吗?
    • @TheGreat:它是insert syntax的一部分
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多