如何將資料從一個欄位逐行復制到另一個欄位?


要將資料從一個欄位逐行復制到另一個欄位,請使用 UPDATE 命令。

我們首先建立一個表 −

mysql> create table DemoTable
   (
   StudentId int,
   StudentFirstName varchar(20),
   StudentMarks int default 0
   );
Query OK, 0 rows affected (0.49 sec)

下面是使用 insert 命令在表中插入記錄的查詢 −

mysql> insert into DemoTable(StudentId,StudentFirstName) values(89,'Larry');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentId,StudentFirstName) values(35,'Robert');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(StudentId,StudentFirstName) values(48,'Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentId,StudentFirstName) values(78,'David');
Query OK, 1 row affected (0.61 sec)

下面是使用 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;
Query OK, 4 rows affected (0.34 sec)
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)

更新於: 2019 年 7 月 30 日

2K+ 瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.