当前位置:网站首页>MySql 怎么查出符合条件的最新的数据行?
MySql 怎么查出符合条件的最新的数据行?
2022-07-03 09:35:00 【小目标青年】
平时做业务,经常是需要查什么什么什么的最新的一条数据。
那至于最新这个概念, 对于产品来说,经常会说的是 时间顺序,最新也就是 最近的意思。
结合示例:
这是一张记录人员来访的记录表。
数据表里的数据准确记录了每个人来访时带的帽子颜色、时间、人员编码(每个人唯一)。
数据样例:

需要做到的是 :
拿出符合条件的最新的来访记录。
你会最怎么做?
先实现一点的, 取出 A101 这个人员编码的 最新来访记录 。
首先先展示错误的sql示例: 想当然地使用max() 函数。
SELECT MAX(id) AS id ,user_code,cap_color,create_time FROM vist_record WHERE user_code='A101' ;
查询结果(错误的结果):

显然咋一看出来的数据有模有样。
但是其实是错的,是按照条件筛选完,然后取了符合条件的最大的一个id值,单独替换了 id。
正确的数据是 :

那是不是max(id) 用不了了?
正确用法(将符合条件的最大id值作为条件):
SELECT
id,user_code,cap_color,create_time
FROM vist_record
WHERE id IN (SELECT MAX(id) AS id FROM vist_record WHERE user_code='A101' )
查询结果:
但是看到上面使用子查询的这种方式,
大家心里面肯定也已经在暗暗地骂娘, 拿个最新数据这么麻烦?
有没有简单一点的?
有。
比如说,我们已经确定了, id是自增的,id最大的数据(符合条件的数据) 就是最新的。
那么我们就可以使用倒序 DESC 来取最新数据:
DESC 也就是 倒序/降序 。
PS:
使用倒序查找:
SELECT *
FROM vist_record
WHERE user_code='A101'
ORDER BY id DESC
LIMIT 1;
查询结果:

或者根据时间倒序:
SELECT *
FROM vist_record
WHERE user_code='A101'
ORDER BY create_time DESC
LIMIT 1;
查询结果:

就这么简单实现了吗?
那么我们如果需求要的不是指定A101 要的是涉及到的每一个人的最新数据呢?
也就是存在多组的概念。
每一类的符合条件的最新数据
橙色框就是 A101 、B202 、 C303 分别的最新记录 , 我们要取出来。
错误示例:
SELECT MAX(id) AS id ,user_code,cap_color,create_time FROM vist_record GROUP BY user_code
错误的筛选结果:

正确编码:
SELECT id ,user_code,cap_color,create_time FROM vist_record WHERE id in
(
SELECT MAX(id) AS id FROM vist_record GROUP BY user_code
)
好了,该篇就先到这吧。
边栏推荐
猜你喜欢

Pytoch has been installed, but vs code still displays no module named 'torch‘

mysql5.7安装和配置教程(图文超详细版)

Drop out (pytoch)

Timo background management system

Unity learning notes: personal learning project "crazy genius Edgar" error correction document

Ut2012 learning notes

Jupiter notebook changing font style and font size

权重衰退(PyTorch)

Unity group engineering practice project "the strongest takeaway" planning case & error correction document

I really want to be a girl. The first step of programming is to wear women's clothes
随机推荐
The story of a 30-year-old tester struggling, even lying flat is extravagant
Leetcode skimming ---10
Ut2012 learning notes
CSDN, I'm coming!
分组函数之rollup、cube函数、grouping sets函数
FileNotFoundError: Could not find module ‘... dll‘ (or one of its dependencies).
Knowledge map reasoning -- hybrid neural network and distributed representation reasoning
[untitled]
Unity学习笔记:联网游戏Pixel Adventure 1学习过程&纠错心得
Leetcode skimming ---367
High imitation bosom friend manke comic app
Pytoch has been installed, but vs code still displays no module named 'torch‘
Several problems encountered in installing MySQL under MAC system
Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported
[SQL] an article takes you to master the operations related to query and modification of SQL database
R language classification
Tensorflow—Image segmentation
Ind FHL first week
Timo background management system
2021-09-22
