27

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
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
Codesl
  • 547
  • 2
  • 5
  • 10

2 Answers2

106

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
fancyPants
  • 50,732
  • 33
  • 89
  • 96
  • What is advantage of using `t1`, `t2`? – Gathide May 09 '20 at 17:15
  • 1
    @Gathide Less typing :) I made it a habit to always add the table name to a column in a select clause for example. Short aliases help a lot here. – fancyPants May 09 '20 at 19:38
  • This is not working for me... I should also note that I did not alter the table which is the first line you have because I already have the column existing.. I don't know if that is what's causing issues... Any theories on that? – Adan Vivero Sep 23 '22 at 22:07
15

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;
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
  • 23
    Yeah sure, copy my answer. – fancyPants Dec 09 '14 at 10:06
  • 6
    @fancyPants the timestamps suggest that Saharsh submitted his answer first. – Martin Schapendonk Dec 09 '14 at 10:22
  • @MartinSchapendonk He edited his answer afterwards, after he saw mine. – fancyPants Dec 09 '14 at 10:28
  • 7
    @fancyPants did you even look at the edit? He only added a semicolon (which your solution doesn't even have). The two of you gave the same answer in the same minute. It happens. No hard feelings. – Martin Schapendonk Dec 17 '14 at 11:07
  • 3
    @MartinSchapendonk FYI, when you edit an answer in the first 5 minutes, you can't have a look at it later. Go ahead, have a try on your next answer, there won't be a `edited ` link in the first 5 minutes. But sure, defend him. Soon everyone writes a "asdf" answer first and edits later, just to be the first to answer. – fancyPants Dec 17 '14 at 11:28
  • 5
    @fancyPants if that is true, than that would be a very nasty way to hijack the first answer and I would take everything back I said earlier. – Martin Schapendonk Dec 17 '14 at 12:39
  • This is not working for me in adding the values into the table... – Adan Vivero Sep 23 '22 at 22:06
  • I'm using this answer, but I'm getting a Syntax error: Unexpected 'INNER'. Any thoughts? – A Dolegowski Aug 18 '23 at 18:17