如何仅更新MySQL表中一个值,而该值是从同一表中按降序排列选择的?
为此,请使用带有 LIMIT 子句的 ORDER BY DESC。ORDER BY DESC 按降序排列,而 LIMIT 设置您想要记录的数量。这里,我们将设置 **LIMIT 1**,因为我们只需要一条记录。让我们先创建一个表:
mysql> create table DemoTable ( StudentName varchar(100), StudentMarks int ); Query OK, 0 rows affected (0.54 sec)
使用 INSERT 命令在表中插入一些记录:
mysql> insert into DemoTable values('Chris',45); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Bob',78); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Mike',34); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Robert',67); Query OK, 1 row affected (0.16 sec)
使用 SELECT 语句显示表中的所有记录:
mysql> select *from DemoTable;
这将产生以下输出:
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris | 45 | | Bob | 78 | | Mike | 34 | | Robert | 67 | +-------------+--------------+ 4 rows in set (0.00 sec)
以下是按降序排列仅更新 MySQL 表中单个值的查询:
mysql> update DemoTable set StudentName='Adam' order by StudentMarks DESC LIMIT 1; Query OK, 1 row affected (0.10 sec) Rows matched: 1 Changed: 1 Warnings: 0
让我们再次检查表记录:
mysql> select *from DemoTable;
这将产生以下输出:
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris | 45 | | Adam | 78 | | Mike | 34 | | Robert | 67 | +-------------+--------------+ 4 rows in set (0.00 sec)
广告