如何使用具有相同外键的其他行的值更新行

How to update rows with the value from other rows that have the same foreign key

提前致谢!这是我的:

primary_key | foreign_key   | field_to_update
---------------------------------------------
          1 |             1 |              A 
          2 |             1 |              - 
          3 |             2 |              B
          4 |             2 |              -
---------------------------------------------

预期结果:

primary_key | foreign_key   | field_to_update
---------------------------------------------
          1 |             1 |              A 
          2 |             1 |              A 
          3 |             2 |              B
          4 |             2 |              B
---------------------------------------------

我将如何进行?我觉得我做不到:

UPDATE table
SET field_to_update = field_to_update
WHERE ...

这似乎没有意义。有人可以帮我解决这个问题吗?

您可以将 updatejoin 一起使用:

update t join
       (select foreign_key, max(field_to_update) as field_to_update
        from t 
        group by foreign_key
       ) tt
       on t.foreign_key = tt.foreign_key
    set t.field_to_update = tt.field_to_update
    where t.field_to_update is null;