
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update a Column Based on Another MySQL Table's Column
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)
Advertisements