在 MySQL 中更新整行?


在 MySQL 中更新整個行,需要使用 UPDATE 命令。例如,更新整行,必須知道主鍵列。下面的語法用於更新一行。

UPDATE yourTableName SET yourColumnName1 = ’yourValue1’ ,yourColumnName2 = ’yourValue2’ ,
   yourColumnName3 = ’yourValue3’ ,.......................N
   WHERE yourPrimaryKeyColumnName = yourValue;

為了理解上述語法,建立一個表。建立表的查詢如下 −

mysql> create table UpdateEntireRowDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> Age int,
   -> Marks int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.74 sec)

使用 insert 命令在表中插入一些記錄。查詢如下 −

mysql> insert into UpdateEntireRowDemo(Name,Age,Marks) values('Sam',23,78);
Query OK, 1 row affected (0.32 sec)

mysql> insert into UpdateEntireRowDemo(Name,Age,Marks) values('Mike',21,99);
Query OK, 1 row affected (0.16 sec)

mysql> insert into UpdateEntireRowDemo(Name,Age,Marks) values('Carol',26,80);
Query OK, 1 row affected (0.11 sec)

mysql> insert into UpdateEntireRowDemo(Name,Age,Marks) values('John',22,71);
Query OK, 1 row affected (0.16 sec)

mysql> insert into UpdateEntireRowDemo(Name,Age,Marks) values('Bob',29,89);
Query OK, 1 row affected (0.16 sec)

mysql> insert into UpdateEntireRowDemo(Name,Age,Marks) values('David',25,68);
Query OK, 1 row affected (0.20 sec)

mysql> insert into UpdateEntireRowDemo(Name,Age,Marks) values('Larry',31,91);
Query OK, 1 row affected (0.12 sec)

使用 select 語句顯示錶中所有記錄。查詢如下 −

mysql> select *from UpdateEntireRowDemo;

以下是輸出 −

+----+-------+------+-------+
| Id | Name  | Age  | Marks |
+----+-------+------+-------+
|  1 | Sam   |   23 |    78 |
|  2 | Mike  |   21 |    99 |
|  3 | Carol |   26 |    80 |
|  4 | John  |   22 |    71 |
|  5 | Bob   |   29 |    89 |
|  6 | David |   25 |    68 |
|  7 | Larry |   31 |    91 |
+----+-------+------+-------+
7 rows in set (0.00 sec)

以下是 MySQL 中更新整行的查詢。這裡將更新 ID 為 5 的行。

查詢如下 −

mysql> update UpdateEntireRowDemo
   -> set Name = 'James',Age = 19,Marks = 78
   -> where Id = 5;
Query OK, 1 row affected (0.12 sec)
Rows matched: 1 Changed: 1 Warnings: 0

現在你可以檢查整行是否已更新。查詢如下 −

mysql> select *from UpdateEntireRowDemo where Id = 5;

以下是輸出 −

+----+-------+------+-------+
| Id | Name  | Age  | Marks |
+----+-------+------+-------+
|  5 | James | 19   |    78 |
+----+-------+------+-------+
1 row in set (0.00 sec)

讓我們看看錶中的所有記錄。

mysql> select *from UpdateEntireRowDemo;

輸出顯示整行已成功更新

+----+-------+------+-------+
| Id | Name  | Age  | Marks |
+----+-------+------+-------+
|  1 | Sam   |   23 |    78 |
|  2 | Mike  |   21 |    99 |
|  3 | Carol |   26 |    80 |
|  4 | John  |   22 |    71 |
|  5 | James |   19 |    78 |
|  6 | David |   25 |    68 |
|  7 | Larry |   31 |    91 |
+----+-------+------+-------+
7 rows in set (0.00 sec)

更新時間: 30-6 月-2020

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告