如何使用内部连接更新行

Posted

技术标签:

【中文标题】如何使用内部连接更新行【英文标题】:How update row with inner joins 【发布时间】:2020-09-03 09:46:56 【问题描述】:

我有这个选择语句,我在其中找到了两行,我想更新一个特定的列:

select * from murex.STPDLV_ENTRY_TABLE a 
inner join (select DLV_FLOW_XX, max(TS_TIME_LONG) AS MaxDateTime from murex.STPDLV_ENTRY_TABLE group by DLV_FLOW_XX) b 
on a.DLV_FLOW_XX = b.DLV_FLOW_XX
and a.TS_TIME_LONG=b.MaxDateTime
and a.DLV_FLOW_XX in (3741539,4044126,3741551)
and a.STP_UDF9 !='Posted';

我试过了:

update STPDLV_ENTRY_TABLE a
set a.STP_UDF9 = 'Posted'
where
inner join (select DLV_FLOW_XX, max(TS_TIME_LONG) AS MaxDateTime from murex.STPDLV_ENTRY_TABLE group by DLV_FLOW_XX) b 
on a.DLV_FLOW_XX = b.DLV_FLOW_XX
and a.TS_TIME_LONG=b.MaxDateTime
and a.DLV_FLOW_XX in (3741539,4044126,3741551);

如何正确构造更新查询?

解决方案:

update (select * 
        from STPDLV_ENTRY_TABLE a 
        inner join (select DLV_FLOW_XX
                           , max(TS_TIME_LONG) AS MaxDateTime 
                    from STPDLV_ENTRY_TABLE 
                    group by DLV_FLOW_XX) b 
        on a.DLV_FLOW_XX = b.DLV_FLOW_XX
        and a.TS_TIME_LONG = b.MaxDateTime
        and a.DLV_FLOW_XX in (3741539,4044126,3741551)
        and a.STP_UDF9 !='Posted') test
set test.STP_UDF9 = 'Posted';

【问题讨论】:

你想更新什么 抱歉我已经编辑了脚本 ***.com/questions/tagged/oracle+join+sql-update 【参考方案1】:

只需将您的查询作为表格:

update (select * 
        from STPDLV_ENTRY_TABLE a 
        inner join (select DLV_FLOW_XX
                           , max(TS_TIME_LONG) AS MaxDateTime 
                    from STPDLV_ENTRY_TABLE 
                    group by DLV_FLOW_XX) b 
        on a.DLV_FLOW_XX = b.DLV_FLOW_XX
        and a.TS_TIME_LONG = b.MaxDateTime
        and a.DLV_FLOW_XX in (3741539,4044126,3741551)
        and a.STP_UDF9 !='Posted') test
set test.STP_UDF9 = 'Posted';

这是一个演示:

DEMO

【讨论】:

【参考方案2】:

对我来说,merge 看起来是一个更好/更简单的选择。

MERGE INTO stpdlv_entry_table a
     USING (  SELECT dlv_flow_xx, MAX (ts_time_long) AS maxdatetime
                FROM murex.stpdlv_entry_table
            GROUP BY dlv_flow_xx) b
        ON (    a.dlv_flow_xx = b.dlv_flow_xx
            AND a.ts_time_long = b.maxdatetime)
WHEN MATCHED
THEN
   UPDATE SET a.stp_udf9 = 'Posted'
           WHERE a.dlv_flow_xx IN (3741539, 4044126, 3741551);

【讨论】:

以上是关于如何使用内部连接更新行的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Spark sql 在 Databricks 中使用内部联接更新 Databricks Delta 表

如何将mysql内部连接结果从行分组到列

mysql - 如何强制更改内部连接的评估顺序?

Magento 的 Lightspeed 连接器 - 如何禁用来自 Lightspeed 的描述更新,以便它们仅在 Magento 中进行管理?

从内部连接更新列[重复]

使用内部连接更新 [重复]