MySQL 分组去重排序获取最新的一条记录,MySQL group by oder by 取最新一条数据, mysql | 去重查询

只排序没有分组之前数据:

使用:ORDER BY aaci.component_id, aasi.create_time desc
在这里插入图片描述

分组去重,排序之后数据

ORDER BY前添加GROUP BY aaci.component_id ,使用 component_id 进行排序

SELECT aasi.wt_id as turbineId, aafi.function_id as functionId, aafi.desc as `desc`,  
aaci.component_id as componentId, aaci.component_name as componentName,
aasi.peak_peak_value as peakPeakValue, aasi.create_time as createTime
FROM ais_auxiliary_component_info aaci
LEFT JOIN ais_auxiliary_signal_info aasi 
ON aasi.component_id=aaci.component_id
LEFT JOIN ais_auxiliary_function_info aafi
ON aaci.function_id=aafi.function_id
WHERE aafi.function_id = 1 and aasi.wt_id = 1 
GROUP BY aaci.component_id
ORDER BY aaci.component_id, aasi.create_time desc

效果:
在这里插入图片描述

看出来peakPeakValue和createTime 并不是最新的一条数据

解决方法

select中 使用
SUBSTRING_INDEX(GROUP_CONCAT(aasi.peak_peak_value ORDER BY aasi.create_time desc), ',', 1) as peakPeakValue
来获取最新的peakPeakValue数据;
max(aasi.create_time) as createTime 来获取createTime最新数据

SELECT aasi.wt_id, aafi.function_id, aafi.desc, aaci.component_id, aaci.component_name ,aasi.id as aasiId,
SUBSTRING_INDEX(GROUP_CONCAT(aasi.peak_peak_value ORDER BY aasi.create_time desc), ',', 1) as peakPeakValue, max(aasi.create_time) as createTime
FROM ais_auxiliary_component_info aaci
LEFT JOIN ais_auxiliary_signal_info aasi 
ON aasi.component_id=aaci.component_id
LEFT JOIN ais_auxiliary_function_info aafi
ON aaci.function_id=aafi.function_id
WHERE aafi.function_id=1 and aasi.wt_id=1 
GROUP BY aaci.component_id
ORDER BY aaci.component_id, aasi.create_time desc

效果:
在这里插入图片描述

解决思路:

首先进行分组去重进行排序,然后使用GROUP_CONCAT函数对所需要列,进行组合起来,然后使用时间进行排序,将最新的数据放在第一个,然后再使用SUBSTRING_INDEX()函数取第一个数据就行,时间使用max()函数获取最新时间即可。

group_concat函数

group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator '分隔符'] )

SUBSTRING_INDE函数

substring_index(str,delim,count)
    str:要处理的字符串
    delim:分隔符
    count:计数
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小诺大人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值