id 最高且字段等于变量的 MySQL UPDATE 查询?
语法如下
update yourTableName set yourColumnName1=yourValue where yourColumnName2=yourValue order by yourIdColumnName DESC LIMIT 1;
为理解上述语法,我们创建一个表。创建表的查询如下
mysql> create table UpdateWithHighestDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserStatus tinyint, -> UserRank int -> ); Query OK, 0 rows affected (0.61 sec)
使用 insert 命令将一些记录插入表中。
查询如下
mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,78); Query OK, 1 row affected (0.12 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,118); Query OK, 1 row affected (0.18 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,223); Query OK, 1 row affected (0.62 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,225); Query OK, 1 row affected (0.12 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,227); Query OK, 1 row affected (0.14 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,230); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录。
查询如下
mysql> select *from UpdateWithHighestDemo;
以下是输出
+--------+------------+----------+ | UserId | UserStatus | UserRank | +--------+------------+----------+ | 1 | 1 | 78 | | 2 | 0 | 118 | | 3 | 1 | 223 | | 4 | 1 | 225 | | 5 | 0 | 227 | | 6 | 0 | 230 | +--------+------------+----------+ 6 rows in set (0.00 sec)
以下是更新列的查询
mysql> update UpdateWithHighestDemo -> set UserStatus=1 where UserRank=230 order by UserId DESC LIMIT 1; Query OK, 1 row affected (0.19 sec) Rows matched: 1 Changed: 1 Warnings: 0
让我们使用 select 语句检查和显示表中的记录。
查询如下
mysql> select *from UpdateWithHighestDemo;
以下是输出
+--------+------------+----------+ | UserId | UserStatus | UserRank | +--------+------------+----------+ | 1 | 1 | 78 | | 2 | 0 | 118 | | 3 | 1 | 223 | | 4 | 1 | 225 | | 5 | 0 | 227 | | 6 | 1 | 230 | +--------+------------+----------+ 6 rows in set (0.00 sec)
现在,如果你希望使用最高 id 进行更新,ORDER BY 子句是很有用的。在上文的示例输出中,最高的“UserId”=6,UserStatus 为 1。
让我们将 UserStatus 更新为 0。
查询如下
mysql> update UpdateWithHighestDemo -> set UserStatus=0 order by UserId DESC LIMIT 1; Query OK, 1 row affected (0.18 sec) Rows matched: 1 Changed: 1 Warnings: 0
使用 select 语句检查表中的记录。
查询如下
mysql> select *from UpdateWithHighestDemo; +--------+------------+----------+ | UserId | UserStatus | UserRank | +--------+------------+----------+ | 1 | 1 | 78 | | 2 | 0 | 118 | | 3 | 1 | 223 | | 4 | 1 | 225 | | 5 | 0 | 227 | | 6 | 0 | 230 | +--------+------------+----------+ 6 rows in set (0.00 sec)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP