只排序没有分组之前数据:
使用: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:计数