我想在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 中。请解释一下如何实现这个场景?
最佳答案
您只需五个步骤即可完成:
启动数据库事务。
将
table1
中的行选择到变量id2
、name2
和title2
中。使用
ON DUPLICATE KEY UPDATE
在table2
上插入或更新:insert into table2 (id, name, title) values (id2, name2, title2) on duplicate key update name = name2, title = title2
从
table1
中删除。不要截断。截断可能会使交易无效。提交事务。
关于mysql - 如何在mysql中进行scd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144788/