如何在 MySQL 中删除表中的最后一条记录(基于条件)?
要删除表中的最后一条记录(基于条件),您需要使用 ORDER BY DESC 和 LIMIT
1. 语法如下
DELETE FROM yourTableName WHERE yourColumnName1=yourValue ORDER BY yourColumnName2 DESC LIMIT 1;
以上语法将删除表中的最后一条记录(基于条件)。它按降序对列进行排序,并选择第一个元素进行删除。
为了理解以上语法,让我们创建一个表。创建表的查询如下
mysql> create table UserLoginTable -> ( -> Id int NOT NULL AUTO_INCREMENT, -> UserId int, -> UserLoginDateTime datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.94 sec)
使用 insert 命令在表中插入一些记录。查询如下
mysql> insert into UserLoginTable(UserId,UserLoginDateTime) values(2,'2019-01-27 13:47:20'); Query OK, 1 row affected (0.19 sec) mysql> insert into UserLoginTable(UserId,UserLoginDateTime) values(1,'2018-11-28 12:30:12'); Query OK, 1 row affected (0.16 sec) mysql> insert into UserLoginTable(UserId,UserLoginDateTime) values(2,'2019-01-26 11:30:30'); Query OK, 1 row affected (0.20 sec) mysql> insert into UserLoginTable(UserId,UserLoginDateTime) values(1,'2015-03-11 15:23:55'); Query OK, 1 row affected (0.21 sec) mysql> insert into UserLoginTable(UserId,UserLoginDateTime) values(2,'2019-03-21 16:01:56'); Query OK, 1 row affected (0.23 sec)
现在,您可以使用 select 语句显示表中的所有记录。查询如下
mysql> select *from UserLoginTable;
以下是输出
+----+--------+---------------------+ | Id | UserId | UserLoginDateTime | +----+--------+---------------------+ | 1 | 2 | 2019-01-27 13:47:20 | | 2 | 1 | 2018-11-28 12:30:12 | | 3 | 2 | 2019-01-26 11:30:30 | | 4 | 1 | 2015-03-11 15:23:55 | | 5 | 2 | 2019-03-21 16:01:56 | +----+--------+---------------------+ 5 rows in set (0.00 sec)
以下是删除表中最后一条记录(基于条件)的查询
mysql> delete from UserLoginTable where UserId=2 ORDER BY UserLoginDateTime DESC LIMIT 1; Query OK, 1 row affected (0.16 sec)
再次使用 select 语句检查表记录。查询如下
mysql> select *from UserLoginTable;
以下是输出
+----+--------+---------------------+ | Id | UserId | UserLoginDateTime | +----+--------+---------------------+ | 1 | 2 | 2019-01-27 13:47:20 | | 2 | 1 | 2018-11-28 12:30:12 | | 3 | 2 | 2019-01-26 11:30:30 | | 4 | 1 | 2015-03-11 15:23:55 | +----+--------+---------------------+ 4 rows in set (0.00 sec)
最后一条记录已从表中删除,UserId 为 2。
广告