Hello. There was a need to transfer field values ​​from one table to another by comparing data. Here is an example of a table table1

Table1ID Table1Name

  1. Textbook
  2. Notebook
  3. Textbook
  4. Textbook

Example table table2

Table2ID Name Nameid

  1. A pen
  2. Notebook
  3. Textbook
  4. Textbook

Task: Compare 2 tables, if the Name values ​​in the fields are the same, then add the id from table1 to the Nameid field from table2. I use Mysql and php My code

$query = "SELECT * FROM table1 , table2 WHERE Table1Name = Table2Name"; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)) { $query2 = "UPDATE table2 SET Table2Name=".$row[Table1ID]." WHERE Table1Name = Table2Name"; mysql_query($query2); } 

    1 answer 1

    in theory, you can do everything right in the request, without additional code

     update Table2 t2 join Table1 t1 on (Table1Name = Name) set Nameid = t1.id 
    • The fact is that I wanted to add a limit on the records, since the server is located remotely, in the first table there are 500 records, in the second about 700 ... and when I try to start it displays the error "504 Gateway Time-out". - Newcomer
    • Everything is working. Thank you, the server disconnected for a few minutes, but everything changed - Beginner
    • This is very few entries, it should be noted. But well, that turned out - splash58