SQLite inner join - update using values from another table

前端 未结 5 1601
走了就别回头了
走了就别回头了 2020-12-03 05:24

This is quite easy and has been asked multiple times but I can\'t get it to work. The SQL query I think should work is:

    UPDATE table2
       SET dst.a =          


        
5条回答
  •  鱼传尺愫
    2020-12-03 06:05

    I came up with an alternative technique using a TRIGGER and "reversing" the direction of the update, albeit at the cost of a dummy field in the source table.

    In general terms, you have a Master table and an Updates table. You want to update some/all fields of records in Master from the corresponding fields in Updates linked by a key field Key.

    Instead of UPDATE Master SET ... FROM Master INNER JOIN Updates ON Mater.Key = Updates.Key you do the following:

    1. Add a dummy field TriggerField to the Updates table to act as the focus of the trigger.

    2. Create a trigger on this field:

      CREATE TRIGGER UpdateTrigger AFTER UPDATE OF TriggerField ON Updates
      BEGIN
          UPDATE Master SET
              Field1 = OLD.Field1,
              Field2 = OLD.Field2,
              ...
          WHERE Master.Key = OLD.Key
      END;
      
    3. Launch the update process with the following:

      UPDATE Updates SET TriggerField = NULL ;
      

    Notes

    1. The dummy field is merely an anchor for the trigger so that any other UPDATE Updates SET ... won't trigger the update into Master. If you only ever INSERT into Updates then you don't need it (and can remove the OF TriggerField clause when creating the trigger).

    2. From some rough-and-ready timings, this seems to work about the same speed as REPLACE INTO but avoids the feels-slightly-wrong technique of removing and adding rows. It is also simpler if you are only updating a few fields in Master as you only list the ones you want to change.

    3. It is orders of magnitude faster than the other alternative I've seen to UPDATE ... FROM which is:

      UPDATE Master SET
          Field1 = ( SELECT Field1 FROM Updates WHERE Mater.Key = Updates.Key ),
          Field1 = ( SELECT Field1 FROM Updates WHERE Mater.Key = Updates.Key ),
          ...
      ;
      

      Updating six fields over 1700 records was roughly 0.05s for Tony and my methods but 2.50s for the UPDATE ... ( SELECT... ) method.

    4. AFTER UPDATE triggers on Master seem to fire as expected.

提交回复
热议问题