MySQL update table based on another tables value

前端 未结 7 1275
心在旅途
心在旅途 2020-11-22 15:20

I have a two tables,

Here is my first table,

ID      SUBST_ID        CREATED_ID
1       031938          TEST123
2       930111          COOL123
3             


        
相关标签:
7条回答
  • 2020-11-22 15:57
    UPDATE TABLE2
           JOIN TABLE1
           ON TABLE2.SERIAL_ID = TABLE1.SUBST_ID
    SET    TABLE2.BRANCH_ID = TABLE1.CREATED_ID;
    
    0 讨论(0)
  • 2020-11-22 15:57

    You can use this too:

    update TABLE1 set BRANCH_ID = ( select BRANCH_ID from TABLE2 where TABLE1.SUBST_ID = TABLE2.SERIAL_ID)
    

    but with my experience I can say that this way is so slow and not recommend it!

    0 讨论(0)
  • 2020-11-22 15:59
    UPDATE TABLE2
           JOIN TABLE1
           ON TABLE1.SUBST_ID = TABLE2.SERIAL_ID
    SET    TABLE2.BRANCH_ID = TABLE1.CREATED_ID 
    WHERE TABLE2.BRANCH_ID IS NULL or TABLE2.BRANCH_ID='';
    
    0 讨论(0)
  • 2020-11-22 16:00

    I think this should work

    UPDATE secondTable
    JOIN firsTable ON secondTable.SERIAL_ID = firsTable.SUBST_ID
    SET BRANCH_ID = CREATED_ID
    
    0 讨论(0)
  • 2020-11-22 16:03

    It is very simple to update using Inner join query in SQL .You can do it without using FROM clause. Here is an example :

        UPDATE customer_table c 
    
          INNER JOIN  
              employee_table e
              ON (c.city_id = e.city_id)  
    
        SET c.active = "Yes"
    
        WHERE c.city = "New york";
    
    0 讨论(0)
  • 2020-11-22 16:16

    In addition to Tom's answer if you need to repeat the operation frequently and want to save time you can do:

    UPDATE TABLE1
           JOIN TABLE2
           ON TABLE1.SUBST_ID = TABLE2.SERIAL_ID
    SET    TABLE2.BRANCH_ID = TABLE1.CREATED_ID
    WHERE TABLE2.BRANCH_ID IS NULL
    
    0 讨论(0)
提交回复
热议问题