Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a column to a table from another table in Mysql?

I have two tables

  1. table1
  2. table2

Tabel1 contains 2 columns

  1. id
  2. Name

Tabel2 contains 2 columns

  1. id
  2. Age

A want to add age column from table2 to table1 (WHERE table1.id = table2.id)

Then table1 should contains 3 columns

  1. id
  2. Name
  3. Age
like image 871
Codesl Avatar asked Dec 09 '14 10:12

Codesl


2 Answers

First add the column with the appropriate datatype.

ALTER TABLE table1 ADD COLUMN Age TINYINT UNSIGNED NOT NULL DEFAULT 0;

Then update the table, so that the values are "transmitted".

UPDATE table1 t1
INNER JOIN tabel2 t2 ON t1.id = t2.id 
SET t1.Age = t2.Age
like image 200
fancyPants Avatar answered Oct 31 '22 22:10

fancyPants


First add Age column in table1

ALTER TABLE table1 ADD COLUMN Age TINYINT UNSIGNED DEFAULT 0;

then update that column using blow query

UPDATE table1 t1
INNER JOIN Tabel2 t2 ON t1.id = t2.id 
SET t1.age = t2.age;
like image 30
Saharsh Shah Avatar answered Oct 31 '22 21:10

Saharsh Shah