【问题标题】:Update column by join two tables using Oracle通过使用 Oracle 连接两个表来更新列
【发布时间】:2021-03-25 23:58:45
【问题描述】:

我需要使用与其他表的连接来更新表列 我的 SQL 伪代码如下:

 update table1 T1 set T1.user = T2.product where T2.product like '%P12%' 
 and T1.order = T2.order;

我也尝试过使用 JOIN 查询,但使用 Oracle 时出现错误“SQL 命令未正确结束”。

【问题讨论】:

    标签: sql oracle sql-update subquery inner-join


    【解决方案1】:

    在 Oracle 中,您可以使用关联子查询:

    update table1 t1
    set t1.user = (select t2.product from table2 t2 where t1.order = t2.order and t2.product like '%P12%' )
    where exists(select 1 from table2 t2 where t1.order = t2.order and t2.product like '%P12%')
    

    我发现有人会从名为 product 的内容中更新名为 user 的内容,这让我感到非常惊讶 - 但这仍然是您原来的伪代码。

    【讨论】:

    • 我需要编辑我的伪代码,它是 T2.product like '%P12%' 的地方,但是当我在上面的 where 子句中使用相同的时候,它给出的 T2.product 是无效的标识符。
    • @user2907032:需要进入子查询。我编辑了我的答案。
    【解决方案2】:

    在 oracle 中,不允许使用 JOIN 进行更新。

    您可以使用MERGE。它可以使用另一个表来更新一个表。

    MERGE INTO T1
    USING (SELECT T2.PRODUCT,
                  T2.ORDER
             FROM T2 WHERE T2.PRODUCT LIKE '%P12%') T2 
    ON ( T1.ORDER = T2.ORDER )
    WHEN MATCHED THEN UPDATE
       SET T1.USER = T2.PRODUCT
    

    【讨论】:

      猜你喜欢
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      相关资源
      最近更新 更多