從 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 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告