MySQL 在单个查询中更新多个记录?
mysqlmysqli database
首先我们创建一个表 −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Marks1 int, -> Marks2 int, -> Marks3 int -> ); Query OK, 0 rows affected (0.60 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(Marks1,Marks2,Marks3) values(45,67,34); Query OK, 1 row affected (0.33 sec) mysql> insert into DemoTable(Marks1,Marks2,Marks3) values(89,87,56); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(Marks1,Marks2,Marks3) values(87,56,54); Query OK, 1 row affected (0.31 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----+--------+--------+--------+ | Id | Marks1 | Marks2 | Marks3 | +----+--------+--------+--------+ | 1 | 45 | 67 | 34 | | 2 | 89 | 87 | 56 | | 3 | 87 | 56 | 54 | +----+--------+--------+--------+ 3 rows in set (0.00 sec)
这是更新多个记录的查询 −
mysql> update DemoTable -> set Marks1=98,Marks2=96,Marks3=99 -> where Id=1; Query OK, 1 row affected (0.18 sec) Rows matched: 1 Changed: 1 Warnings: 0
让我们再次检查表记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----+--------+--------+--------+ | Id | Marks1 | Marks2 | Marks3 | +----+--------+--------+--------+ | 1 | 98 | 96 | 99 | | 2 | 89 | 87 | 56 | | 3 | 87 | 56 | 54 | +----+--------+--------+--------+ 3 rows in set (0.00 sec)