UPDATING THE TABLE USING OTHER RESULTS

I have the following query that works great

SELECT RecordID, ROW_NUMBER() OVER (ORDER BY (Value1) DESC) AS Rank
FROM Table1

In addition, I have another table (table2) that contains (among others) the RecordID and Rank fields. I would like to update RecordID and Rank in table2 based on the result of the query above. Is it possible?

+6
source share
2 answers

Yes, you can have several tables updatein Postgres:

update table2
    set rank = t1.rank
    from (SELECT RecordID, ROW_NUMBER() OVER (ORDER BY (Value1) DESC) AS Rank
          FROM Table1
         ) t1
    where table2.RecordId = t1.RecordId;
+16
source

What worked for me (in MySQL):

update table2, (SELECT RecordID, ROW_NUMBER() OVER (ORDER BY (Value1) DESC) AS Rank 
    FROM Table1) tempTable 
set table2.Rank = tempTable.Rank 
where table2.RecordId = tempTable.RecordId;
0
source

Source: https://habr.com/ru/post/1589303/


All Articles