将列值从一个表复制到MySQL中的另一个匹配ID
让我们首先创建一个表-
mysql> create table DemoTable1 ( PersonId int, Value int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1 values(100,78); mysql> insert into DemoTable1 values(101,67); mysql> insert into DemoTable1 values(102,89);
使用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 );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2 values(100,NULL) ; mysql> insert into DemoTable2 values(102,NULL);
使用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; Rows matched: 2 Changed: 2 Warnings: 0
让我们再次检查表记录-
mysql> select *from DemoTable2;
这将产生以下输出-
+-----------+--------------+ | StudentId | StudentScore | +-----------+--------------+ | 100 | 78 | | 102 | 89 | +-----------+--------------+ 2 rows in set (0.00 sec)