一、sql去重排序:
需求,对数据库数据按mfrom去重(显示最新数据),并对去重后的数据按mcreated_time进行倒序排列:
sql语句为:
(1)SELECT * FROM messages m WHERE NOT EXISTS (SELECT * FROM messages WHERE m.mfrom = mfrom AND m.mcreated_time < mcreated_time)
GROUP BY m.mfrom ORDER BY m.mcreated_time DESC;
(2)SELECT * FROM messages m WHERE NOT EXISTS (SELECT * FROM messages WHERE m.mfrom = mfrom AND m.mcreated_time < mcreated_time)
ORDER BY m.mcreated_time DESC;
注:(1)、(2)sql语句可达到同样的效果,主要原因为通过NOT EXISTS 语句已经筛选出mfrom对应的那条最新数据,已达到去重的目的,再对其进行按时间综合排序即可。
但如果同一个mfrom含有相同的最大时间,则需使用(2);
二、java分页
要求:对获取的list集合进行分页显示,每页显示pageSize=10条,通过传参id,后续页显示当前id对应的下pageSize个对象,实现分页目的;
(1)传参messageContainerId初始值为" "时:
List<MessageContainerVO> list = new ArrayList<MessageContainerVO>();
// 分页
int sum = 0;
boolean flag = false;
for (int i = 0; i < messageVOList.size(); i++) {
MessageContainerVO messageVO = messageVOList.get(i);
if (flag) {
if (sum < pageSize) {
list.add(messageVO);
sum += 1;
} else {
break;
}
} else {
if (messageContainerId.equals("")) {
list.add(messageVO);
sum += 1;
flag = true;
} else if (messageVO.getMessageContainerId().equals(messageContainerId)) {
flag = true;
}
}
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("informationList", list);
return map;
(2)传参messageId初始值不" "时:
List<InformMessageVO> voList2 = new ArrayList<>();
boolean searched = false;
int sum = 0;
for (int i = 0; i < voList.size(); i++) {
InformMessageVO vo = voList.get(i);
if (searched) {
if (sum < pageSize) {
voList2.add(vo);
sum += 1;
} else {
break;
}
} else {
if (i == 0 && messageId.equals(vo.getMessageId())) { //第一页需显示messageId对应的那一条
voList2.add(vo);
sum += 1;
searched = true;
} else if (i != 0 && messageId.equals(vo.getMessageId())) {//后续页不需要显示messageId对应的那一条
searched = true;
}
}
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("informMessageList", voList2);
return map;