Oracle SQL update based on subquery between two tables

后端 未结 4 575
無奈伤痛
無奈伤痛 2020-12-31 11:51

I am currently writing update statements to keep a query-able table constantly up to date. The schema is identical between both tables and the contents are not important:

相关标签:
4条回答
  • 2020-12-31 12:05

    There are two ways to do what you are trying

    One is a Multi-column Correlated Update

    UPDATE PRODUCTION a
    SET (name, count) = (
      SELECT name, count
      FROM STAGING b
      WHERE a.ID = b.ID);
    

    DEMO

    You can use merge

    MERGE INTO PRODUCTION a
    USING ( select id, name, count 
              from STAGING ) b
    ON ( a.id = b.id )
    WHEN MATCHED THEN 
    UPDATE SET  a.name = b.name,
                a.count = b.count
    

    DEMO

    0 讨论(0)
  • 2020-12-31 12:08

    Without examples of the dataset of staging this is a shot in the dark, but have you tried something like this?

    update PRODUCTION p,
           staging s
    set p.name = s.name  
        p.count = s.count
    where p.id = s.id
    

    This would work assuming the id column matches on both tables.

    0 讨论(0)
  • 2020-12-31 12:11

    Try it ..

    UPDATE PRODUCTION a
    SET (name, count) = (
    SELECT name, count
            FROM STAGING b
            WHERE a.ID = b.ID)
    WHERE EXISTS (SELECT 1
        FROM STAGING b
        WHERE a.ID=b.ID
     );
    
    0 讨论(0)
  • 2020-12-31 12:21

    As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

    However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

    0 讨论(0)
提交回复
热议问题