Search code examples
mysqlselectsql-updateinner-join

Update from Select - Syntax and concept check (mySQL)


I have the following query in MySQL that works as expected:

   SELECT * 
   FROM wa_tmp_listed A 
   INNER JOIN wa_list B 
   ON A.symbol = B.symbol  

This brings back approximately 3500 records. What I what to do is update all of those records into wa_list.

So I believe this query should get me there, but I keep running into errors so wanting to ask if anyone has a suggestion on syntax or if I am wrong conceptually:

UPDATE `wa_list` 
(SELECT * FROM `wa_tmp_listed` A INNER JOIN `wa_list` B ON A.symbol = B.symbol)
SET field1 = A.field1, 
    field2 = A.field2, 
    field3 = A.field3, 
    field4 = A.field4, 
    field5 = A.field5, 
    field6 = A.field6, 
    field7 = A.field7, 
    field8 = A.field8, 
    field9 = A.field9, 
    field10 = A.field10
WHERE A.field1 = B.field1 
AND A.field2 = B.field2 
AND A.field3 = B.field3;

Notes:

  1. A.symbol from the first query equals to A.field2 in the second.

2: For clarity, look for and update all of A.symbol in the wa_tmp_listed table that ARE in the wa_list and then update the fields into wa_list.


Solution

  • This is the right syntax for your query: 1. You can put the where clause in join condition since it is an INNER JOIN and 2. You don't need to update field1,2 and 3 since the values are the same in table A and B

    UPDATE `wa_list` B
         INNER JOIN `wa_tmp_listed` A  
              ON  A.symbol = B.symbol
              AND A.field1 = B.field1 
              AND A.field2 = B.field2 
              AND A.field3 = B.field3
        SET B.field4 = A.field4, 
            B.field5 = A.field5, 
            B.field6 = A.field6, 
            B.field7 = A.field7, 
            B.field8 = A.field8, 
            B.field9 = A.field9, 
            B.field10 = A.field10;