为此,将ORDER BY DESC与LIMIT子句一起使用。ORDER BY DESC的降序排列,其中LIMIT设置所需的记录数。在这里,我们将设置LIMIT 1,因为我们只需要一条记录。让我们首先创建一个表-
mysql> create table DemoTable ( StudentName varchar(100), StudentMarks int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Chris',45); mysql> insert into DemoTable values('Bob',78); mysql> insert into DemoTable values('Mike',34); mysql> insert into DemoTable values('Robert',67);
使用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; 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)