sql 去重排序及 java分頁
一、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)
註:(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("")) {
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;
sql 去重排序及 java分頁