gpt4 book ai didi

mysql - 如何在mysql中进行scd

转载 作者:行者123 更新时间:2023-11-29 09:49:09 25 4
gpt4 key购买 nike

我想在MySQL中进行SCD过程,我有两个完全相同的表,table1总是被截断并且只有新记录。 table2从table1获取记录并维护历史记录。在我的场景中,如果现有数据出现在 table1 中,我想覆盖 table2 中的数据,如果新记录出现在 table1 中,我想将其作为新记录插入到 table2 中。

create table table1(id int, name varchar(2),title varchar(10));
create table table2(id int, name varchar(2),title varchar(10));

这是我上面的示例表结构。如果表包含像 (1,a,hockey) 这样的值,那么我只想将这些数据插入到 table2 中,那么 table1 将被截断。如果我再次使用相同的 ID 将记录插入到 table2,但标题可能会更改在这种情况下,我想覆盖 table2 中的数据,如果出现任何新的 ID,则它将作为新行插入 table2 中。请解释一下如何实现这个场景?

最佳答案

您只需五个步骤即可完成:

  1. 启动数据库事务。

  2. table1 中的行选择到变量 id2name2title2 中。

  3. 使用ON DUPLICATE KEY UPDATEtable2上插入或更新:

    insert into table2 (id, name, title) values (id2, name2, title2)
    on duplicate key update
    name = name2,
    title = title2
  4. table1中删除。不要截断。截断可能会使交易无效。

  5. 提交事务。

关于mysql - 如何在mysql中进行scd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com