Update a column based on another MySQL table’s column

MySQLMySQLi Database

For this, you can use the join concept. Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> Id int,
   -> Name varchar(10)
   -> );
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(100,'Bob');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1;

This will produce the following output −

+------+------+
|   Id | Name |
+------+------+
|  100 | Bob  |
+------+------+
1 row in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable2
   -> (
   -> Id int,
   -> FirstName varchar(10)
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(100,'Adam');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable2;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Adam      |
+------+-----------+
1 row in set (0.00 sec)

Here is the query to update a column based on another MySQL table’s column −

mysql> update DemoTable1
   -> join DemoTable2 on DemoTable1.Id=DemoTable2.Id
   -> set DemoTable1.Name=DemoTable2.FirstName;
Query OK, 1 row affected (0.15 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the record of first table with updated value −

mysql> select * from DemoTable1;

This will produce the following output −

+------+------+
| Id   | Name |
+------+------+
| 100  | Adam |
+------+------+
1 row in set (0.00 sec)
raja
Published on 05-Nov-2019 13:53:40
Advertisements