能否在 MySQL 中从另一张表向一张表中添加一列?


是的,我们可以从另一张表向一张表中添加一列。我们先创建两个表。创建表的查询如下−

<FirstTable>

mysql> create table FirstTable
   -> ( 
   -> UserId int,
   -> UserName varchar(20)
   -> );
Query OK, 0 rows affected (1.48 sec)

现在创建第二张表。创建第二张表的查询如下 −

<SecondTable>

mysql> create table SecondTable
   -> (
   -> UserId int,
   -> UserAge int
   -> );
Query OK, 0 rows affected (1.57 sec)

现在,向第一张表添加 Age 列。首先,添加 Age 列,然后使用 UPDATE 命令将该 Age 列设置为 SecondTable 的 UserAge 列。查询如下 −

mysql> ALTER TABLE FirstTable ADD COLUMN Age TINYINT UNSIGNED DEFAULT 0;
Query OK, 0 rows affected (1.53 sec)
Records: 0 Duplicates: 0 Warnings: 0

现在,此处是查询,用于将第一张表的 Age 列更新为 SecondTable 的 UserAge 列。查询如下 −

mysql> UPDATE FirstTable tbl1
   -> INNER JOIN SecondTable tbl2 ON tbl1.UserId = tbl2.UserId
   -> SET tbl1.Age = tbl2.UserAge;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0

现在使用 DESC 命令查看第一张表的描述。查询如下 −

mysql> desc FirstTable;

下面的输出显示我们已成功从另一张表添加一列 −

+----------+---------------------+------+-----+---------+-------+
| Field    | Type                | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| UserId   | int(11)             | YES  |     | NULL    |       |
| UserName | varchar(20)         | YES  |     | NULL    |       |
| Age      | tinyint(3) unsigned | YES  |     | 0       |       |
+----------+---------------------+------+-----+---------+-------+
3 rows in set (0.53 sec)

更新于: 2019 年 7 月 30 日

2K+ 次浏览

开启你的 事业

通过完成课程来获得认证

开始
广告
© . All rights reserved.