从 MySQL 中的一张表复制列值到另一张表中,匹配各个 ID


我们先创建一个表−

mysql> create table DemoTable1
(
   PersonId int,
   Value int
);
Query OK, 0 rows affected (0.64 sec)

用 insert 命令往表中插入一些记录−

mysql> insert into DemoTable1 values(100,78);
Query OK, 1 row affected (0.46 sec)
mysql> insert into DemoTable1 values(101,67);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1 values(102,89);
Query OK, 1 row affected (0.19 sec)

用 select 语句显示表中的所有记录−

mysql> select *from DemoTable1;

会得到以下输出−

+----------+-------+
| PersonId | Value |
+----------+-------+
|      100 |    78 |
|      101 |    67 |
|      102 |    89 |
+----------+-------+
3 rows in set (0.00 sec)

以下是创建第二个表所需的查询。

mysql> create table DemoTable2
(
   StudentId int,
   StudentScore int
);
Query OK, 0 rows affected (0.57 sec)

用 insert 命令往表中插入一些记录−

mysql> insert into DemoTable2 values(100,NULL) ;
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable2 values(102,NULL);
Query OK, 1 row affected (0.22 sec)

用 select 语句显示表中的所有记录−

mysql> select *from DemoTable2;

会得到以下输出−

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
|       100 |         NULL |
|       102 |         NULL |
+-----------+--------------+
2 rows in set (0.00 sec)

以下是复制列值从一个表到另一个表中匹配的 id 的查询−

mysql> update DemoTable1, DemoTable2 set DemoTable2.StudentScore = DemoTable1.Value where DemoTable2.StudentId=DemoTable1.PersonId;
Query OK, 2 rows affected (0.13 sec)
Rows matched: 2 Changed: 2 Warnings: 0

我们再次查看下表中的记录−

mysql> select *from DemoTable2;

会得到以下输出−

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
|       100 |           78 |
|       102 |           89 |
+-----------+--------------+
2 rows in set (0.00 sec)

更新于: 2019 年 9 月 26 日

985 次浏览

开启你的职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.