【问题标题】:Sync result of SQL Server view and table MySQLSQL Server 视图和表 MySQL 的同步结果
【发布时间】:2021-10-14 08:53:52
【问题描述】:

我在 SQL Server 中有一个包含许多列的表,并且我已将部分数据移至 MySQL。我在 SQL Server 中的表上创建了一个视图或函数,这两个数据库必须每天通过作业同步一次。因为这个视图的数据可能每天都在变化。

视图返回一个包含 3 列的表:(charvarcharvarchar)它们都不是唯一键或主键。

我的解决办法是:

  1. 创建工作
  2. 在 SQL Server 上执行视图
  3. 返回视图结果
  4. 在 MySQL 中创建 3 列的临时表
  5. 将结果视图从 SQL Server 移动到临时表
  6. 如果之前不存在,则将临时表中的记录一一移动到新表中
  7. 删除临时表

要在不使用临时表的情况下进行传输,我想使用以下类型的查询,但找不到正确的查询。这就是我使用临时表的原因:

insert into new_table
    values (array of records) where record if not exist in new table.

对于我上面提到的解决方案,我使用了以下查询:

insert into new_table
    select *
    from temp_table
    where not exist new_table.column = temp_table.column

您有更好的建议,即可以获取新记录并将其添加到以前的记录中吗?

【问题讨论】:

    标签: mysql sql-server


    【解决方案1】:

    它应该看起来更像这样:

    insert into new_table
        select *
        from temp_table
        where not exists (
            select 1 
            from new_table
            where new_table.column = temp_table.column            
        )
    

    或者这个:

    insert into new_table
        select *
        from temp_table
        where not exists (
            select 1 
            from new_table
            where new_table.column = temp_table.column
                and new_table.column2 = temp_table.column2
                and new_table.column3 = temp_table.column3         
        )
    

    【讨论】:

    • 你知道比做中间表更好的方法吗?在我看来,最好的方法是从源表中读取添加的记录,然后直接将它们移动到目标表中。
    • 可以这样做,但暂存表仍然很常见。它们通过允许数据库做出更好的估计以及内存和页面授权来帮助提高性能,因为最终插入的所有内容都在同一个数据库中,它们有助于避免对实时目标表的破坏,并且它们使匹配记录变得更容易,因此您可以合并或跳过已经存在的记录。
    猜你喜欢
    • 2012-02-03
    • 2012-12-24
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多