【问题标题】:How to effectively Merge in sql如何有效地在sql中合并
【发布时间】:2021-04-15 10:00:20
【问题描述】:

我有一个源表。

id  description             test
12  this is the some value   0
10  this is the old value    5

还有一个临时表。(包含需要在源表中更新的最新更改)

id  description                 test
10  this is the new value        15
14  this is the some new value   5

所需的输出是-> select * from source_table; 应该给我:

id  description                 test
10  this is the new value        15
14  this is the some new value   5
12  this is the some value       0

尝试使用类似的东西-

merge into source_table using temp_table 
    on source_table.id = temp_table.id
    when matched then 
        delete;
insert into source_table (select * from temp_table);

任何建议如何在 1 个单一查询中实现这一点(我试图避免更新)?

【问题讨论】:

  • “我试图避免更新”,为什么?
  • 试图概括这一点,这将在不知道列名的情况下对许多表运行,并且更新本质上很慢(观察到)。
  • insert into source_table (select * from temp_table) 是一个没有表定义的相当危险的概括。
  • 是的,但是我在创建这两个表时使用了类似的东西create table temp_table like source_table; -> 所有新的更改都将出现在临时表中,最后我只需要将所有数据都包含在 source_table 中
  • 我要解决的实际问题是:"delete from $tableName where $dpPrimaryKey in " (select $PrimaryKey from $tempTableName); insert into $tableName (select * from $tempTableName);" 我有这 2 个单独的语句,我想在 1 个查询中获得所需的结果。所以我正在探索 Merge / docs.snowflake.com/en/sql-reference/transactions.html

标签: sql merge query-optimization snowflake-cloud-data-platform


【解决方案1】:

如果要查询,可以运行:

select id, description, test
from temp
union all
select id, description, test
from source
where not exists (select 1 from temp t where source.id = temp.id);

如果要修改数据:

merge into source_table
    using temp_table 
    on source_table.id = temp_table.id
when matched then 
    update set source_table.test = temp_table.test
when not matched then
    insert into source_table (id, description, test)
        values (temp_table.id, temp_table.description, temp_table.test);

相对于merge 的普通文档,您的命名约定有点混乱。典型的命名方式会将“目标”称为您所说的“源”,然后“源”是temp_table 中的新数据。

【讨论】:

  • 在合并的情况下,正如我提到的,我希望避免使用更新,因为在概括时,我希望对许多表运行相同的查询,并且我不会有单独的列名要更新。跨度>
  • 是的,我想修改 source_table。
  • 我要解决的实际问题是:"delete from $tableName where $dpPrimaryKey in " (select $PrimaryKey from $tempTableName); insert into $tableName (select * from $tempTableName);" 我有这两个单独的语句,我想在 1 个查询中获得所需的结果。 @Gordon 在概括这一点时有什么建议吗?
  • @tech_geek 。 . .我认为该引用是对update 命令的引用,因此这是在一个语句中完成的。如果您不想使用update,那么您的问题没有意义。这可以满足您的问题。
猜你喜欢
  • 1970-01-01
  • 2011-10-26
  • 1970-01-01
  • 2010-11-03
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
相关资源
最近更新 更多