要将数据从一个字段复制到每一行的另一字段,请使用UPDATE命令。
让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int, StudentFirstName varchar(20), StudentMarks int default 0 );
以下是使用insert命令在表中插入记录的查询-
mysql> insert into DemoTable(StudentId,StudentFirstName) values(89,'Larry'); mysql> insert into DemoTable(StudentId,StudentFirstName) values(35,'Robert'); mysql> insert into DemoTable(StudentId,StudentFirstName) values(48,'Chris'); mysql> insert into DemoTable(StudentId,StudentFirstName) values(78,'David');
以下是查询以使用select命令显示表中的记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+------------------+--------------+ | StudentId | StudentFirstName | StudentMarks | +-----------+------------------+--------------+ | 89 | Larry | 0 | | 35 | Robert | 0 | | 48 | Chris | 0 | | 78 | David | 0 | +-----------+------------------+--------------+ 4 rows in set (0.00 sec)
以下是将数据从一个字段复制到每一行的另一个字段的查询。在这里,我们将所有StudentId的值复制到StudentMarks-
mysql> update DemoTable set StudentMarks=StudentId; Rows matched: 4 Changed: 4 Warnings: 0
让我们显示表中的所有记录以检查所有行是否已更新-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+------------------+--------------+ | StudentId | StudentFirstName | StudentMarks | +-----------+------------------+--------------+ | 89 | Larry | 89 | | 35 | Robert | 35 | | 48 | Chris | 48 | | 78 | David | 78 | +-----------+------------------+--------------+ 4 rows in set (0.00 sec)