Updating a MySQL table with values from another table?

MySQLMySQLi Database

We can update another table with the help of inner join. Let us create two tables.

Creating a table

mysql> CREATE table tblFirst
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.48 sec)

Inserting records

mysql> INSERT into tblFirst values(1,'John');
Query OK, 1 row affected (0.17 sec)

mysql> INSERT into tblFirst values(2,'Bob');
Query OK, 1 row affected (0.26 sec)

mysql> INSERT into tblFirst values(3,'David');
Query OK, 1 row affected (0.20 sec)

Displaying all records

mysql> SELECT * from tblFirst;

The following is the output

+------+-------+
| id   | name  |
+------+-------+
| 1    | John  |
| 2    | Bob   |
| 3    | David |
+------+-------+
3 rows in set (0.00 sec)

Creating second table

mysql> CREATE table UpdTable
   -> (
   -> IncId int auto_increment,
   -> primary key(IncId),
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.57 sec)

Inserting records

mysql> INSERT into UpdTable(id,name) values(1,'Taylor');
Query OK, 1 row affected (0.12 sec)

mysql> INSERT into UpdTable(id,name) values(2,'jason');
Query OK, 1 row affected (0.24 sec)

mysql> INSERT into UpdTable(id,name) values(3,'carol');
Query OK, 1 row affected (0.14 sec)

mysql> INSERT into UpdTable(id,name) values(4,'john');
Query OK, 1 row affected (0.16 sec)

Displaying all records

mysql> SELECT * from UpdTable;

The following is the output

mysql> SELECT *from UpdTable;
+-------+------+--------+
| IncId | id   | name   |
+-------+------+--------+
| 1     | 1    | Taylor |
| 2     | 2    | jason  |
| 3     | 3    | carol  |
| 4     | 4    | john   |
+-------+------+--------+
4 rows in set (0.00 sec)

Look at the above output, the last name is matching from the first table record. Now, I will write the query for UPDATE −

mysql> UPDATE UpdTable
   -> inner join tblFirst ON (UpdTable.name = tblFirst.name)
   -> SET UpdTable.id = tblFirst.id;
Query OK, 1 row affected (0.19 sec)
Rows matched: 1 Changed: 1 Warnings: 0

We have updated the last record as follows −

The query is

mysql> SELECT * from UpdTable;

The following is the output

+-------+------+--------+
| IncId | id   | name   |
+-------+------+--------+
| 1     | 1    | Taylor |
| 2     | 2    | jason  |
| 3     | 3    | carol  |
| 4     | 1    | john   |
+-------+------+--------+
4 rows in set (0.00 sec)

Look at the sample output. The id is updated, which was 4 but now it is 1.

raja
Published on 22-Oct-2018 09:12:42
Advertisements