【问题标题】:Merge into Table1 using table2, table3 on (multiple conditions)? Missing syntax使用table2,table3 on(多个条件)合并到Table1?缺少语法
【发布时间】:2018-12-13 19:26:09
【问题描述】:

我有table1table2table3, 他们有一个与他们之间相关的连接条件。 假设它是 (ID) 列。

所以问题是,

在使用merge语句的情况下,是否可以 将语法构造成这样:

Merge into Table1 

using table2 , table3
on (table1.ID = Table2.ID , Table2.ID = Table.ID) 
when match then 
update --(definitly table1)
where
table1.something between table2.something and table2.something -- whatever :)
when not match then 
do_nothing  --I think I should type NULL here 

如果这个语法错误,我应该如何调用两个表并使用它们来更新 table1 中的一行?

【问题讨论】:

标签: sql oracle plsql oracle10g sqlplus


【解决方案1】:

我应该如何调用两个表并使用它们来更新 table1 中的一行?

这可以在 Oracle 中通过多种方式实现:

  • 相关子查询
  • 内嵌视图
  • 合并查询

以下代码给出了第三种解决方案(合并语句)的原始注释示例。由于您没有向我们展示您的确切 SQL 尝试和表结构,因此您必须根据您的具体用例进行调整:

MERGE INTO table1 target
-- prepare the dataset to use during the UPDATE
USING (
    SELECT 
        -- following fields will be available in the UPDATE
        t1.id,
        t2.foo,
        t3.bar
    FROM
        -- JOIN conditions between the 3 tables
        table1 t1
        INNER JOIN table2 t2 on t2.id = t1.id
        INNER JOIN table3 t3 on t3.id = t1.id
    WHERE
       -- WHERE clause (if needed)
        t1.zoo = 'blah'
    ) source
-- search records to UPDATE 
ON  (target.id = source.id)
WHEN MATCHED THEN 
    UPDATE SET
        -- UPDATE table1 fieds
        target.value1 = source.foo,
        target.value2 = source.foo
;

注意:虽然此查询使用 Oracle MERGE 语句,但它在概念上并未实现真正的合并操作。合并的概念是 update/insert 查询,而此查询只进行更新,而忽略插入部分。尽管如此,这是在 Oracle 中执行此类相关更新的最简单方法之一...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多