如何在 MySQL 中使用 UPDATE、SET 和 LIMIT 更新具有相同值(非全部)的列?


我们首先创建一个表 −

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

使用插入命令在表中插入一些记录 −

mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name) values('Adam');
Query OK, 1 row affected (0.18 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

+----+--------+
| Id | Name   |
+----+--------+
| 1  | Carol  |
| 2  | Chris  |
| 3  | David  |
| 4  | Bob    |
| 5  | Mike   |
| 6  | Sam    |
| 7  | Robert |
| 8  | Adam   |
+----+--------+
8 rows in set (0.00 sec)

以下是对表进行更新并将列设置为相同值(最后列值除外)的查询 −

mysql> update DemoTable
   -> set Name="John"
   -> limit 7;
Query OK, 7 rows affected (0.20 sec)
Rows matched: 7 Changed: 7 Warnings: 0

让我们再次检查表记录。

mysql> select *from DemoTable;

输出

+----+------+
| Id | Name |
+----+------+
| 1  | John |
| 2  | John |
| 3  | John |
| 4  | John |
| 5  | John |
| 6  | John |
| 7  | John |
| 8  | Adam |
+----+------+
8 rows in set (0.00 sec)

更新于: 30-07-2019

268 次浏览

开启你的职场生涯

完成课程认证

开始学习
广告