在 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)
广告