要更新MySQL中的整个行,请使用UPDATE命令。您需要知道主键列。语法如下,以更新整个行。
UPDATE yourTableName SET yourColumnName1 = ’yourValue1’ ,yourColumnName2 = ’yourValue2’ , yourColumnName3 = ’yourValue3’ ,.......................N WHERE yourPrimaryKeyColumnName = yourValue;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
create table UpdateEntireRowDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> Age int, -> Marks int, -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下-
insert into UpdateEntireRowDemo(Name,Age,Marks) values('Sam',23,78); insert into UpdateEntireRowDemo(Name,Age,Marks) values('Mike',21,99); insert into UpdateEntireRowDemo(Name,Age,Marks) values('Carol',26,80); insert into UpdateEntireRowDemo(Name,Age,Marks) values('John',22,71); insert into UpdateEntireRowDemo(Name,Age,Marks) values('Bob',29,89); insert into UpdateEntireRowDemo(Name,Age,Marks) values('David',25,68); insert into UpdateEntireRowDemo(Name,Age,Marks) values('Larry',31,91);
使用select语句显示表中的所有记录。查询如下-
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更新该行。
查询如下-
update UpdateEntireRowDemo -> set Name = 'James',Age = 19,Marks = 78 -> where Id = 5; Rows matched: 1 Changed: 1 Warnings: 0
现在,您可以检查整个行是否已更新。查询如下-
select *from UpdateEntireRowDemo where Id = 5;
以下是输出-
+----+-------+------+-------+ | Id | Name | Age | Marks | +----+-------+------+-------+ | 5 | James | 19 | 78 | +----+-------+------+-------+ 1 row in set (0.00 sec)
让我们查看表中的所有记录。
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)