MySQL 如何从Mysql中的另一个表向一个表添加一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27376152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:13:14  来源:igfitidea点击:

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

mysqlsqlselectsql-updatealter

提问by Codesl

I have two tables

我有两张桌子

  1. table1
  2. table2
  1. 表格1
  2. 表2

Tabel1 contains 2 columns

表 1 包含 2 列

  1. id
  2. Name
  1. ID
  2. 姓名

Tabel2 contains 2 columns

表 2 包含 2 列

  1. id
  2. Age
  1. ID
  2. 年龄

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

A 想将 table2 中的 age 列添加到 table1 (WHERE table1.id = table2.id)

Then table1 should contains 3 columns

那么 table1 应该包含 3 列

  1. id
  2. Name
  3. Age
  1. ID
  2. 姓名
  3. 年龄

采纳答案by Saharsh Shah

First add Age column in table1

首先在table1中添加Age列

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;

回答by fancyPants

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