MySQL 如何删除最后一条记录(有条件)

MySQL 如何删除最后一条记录(有条件)

要从表格中删除最后一条记录(有条件),您需要使用带有LIMIT的ORDER BY DESC。

1. 语法如下:

DELETE FROM yourTableName WHERE yourColumnName1=yourValue ORDER BY yourColumnName2 DESC LIMIT 1;
Mysql

上述语法将从表格中删除最后一条记录(有条件)。它以降序对列进行排序并选择要删除的第一个元素。

为了理解上面的语法,让我们创建一个表格。创建表格的查询如下:

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)
Mysql

使用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)
Mysql

现在,您可以使用SELECT语句从表格中显示所有记录。查询如下:

mysql> select *from UserLoginTable;
Mysql

以下是输出结果:

+----+--------+---------------------+
| 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

以下是从表格中删除最后一条记录(有条件)的查询:

mysql> delete from UserLoginTable where UserId=2 ORDER BY UserLoginDateTime DESC LIMIT 1;
Query OK, 1 row affected (0.16 sec)
Mysql

再次使用SELECT语句检查表格中的记录。查询如下:

mysql> select *from UserLoginTable;
Mysql

以下是输出结果:

+----+--------+---------------------+
| 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)
Mysql

现在,带有UserId 2的表格中的最后一条记录已被删除。

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册