I have an implementation of datatables serverside pagination.The query builder looks like this:
public static String buildPaginatedQueryForOracle(String baseQuery, PaginationCriteria paginationCriteria) {
StringBuilder sb = new StringBuilder(
"SELECT * FROM (SELECT FILTERED_ORDERED_RESULTS.*, COUNT(1) OVER() total_records, ROWNUM AS RN FROM (SELECT BASEINFO.* FROM ( #BASE_QUERY# ) BASEINFO ) FILTERED_ORDERED_RESULTS #WHERE_CLAUSE# #ORDER_CLASUE# ) WHERE RN > (#PAGE_NUMBER# * #PAGE_SIZE#) AND RN <= (#PAGE_NUMBER# + 1) * #PAGE_SIZE# ");
String finalQuery = null;
int pageNo = paginationCriteria.getPageNumber() / paginationCriteria.getPageSize();
paginationCriteria.setPageNumber(pageNo);
if (!AppUtil.isObjectEmpty(paginationCriteria)) {
finalQuery = sb.toString().replaceAll("#BASE_QUERY#", baseQuery)
.replaceAll("#WHERE_CLAUSE#",
((AppUtil.isObjectEmpty(paginationCriteria.getFilterByClause())) ? "" : " WHERE ")
+ paginationCriteria.getFilterByClause())
.replaceAll("#ORDER_CLASUE#", paginationCriteria.getOrderByClause())
.replaceAll("#PAGE_NUMBER#", paginationCriteria.getPageNumber().toString())
.replaceAll("#PAGE_SIZE#", paginationCriteria.getPageSize().toString());
}
return (null == finalQuery) ? baseQuery : finalQuery;
}
where base_query is the usual string from the dao-impl layer. It does the job well. However, when I want to sort the results by cnt in the order clause ( this particular case uses the cnt to count the rows of another table linked to every row in the first table like this)
SELECT *
FROM (
SELECT FILTERED_ORDERED_RESULTS.*,
COUNT(1) OVER() TOTAL_RECORDS
FROM (
SELECT BASEINFO.*,
ROWNUM AS RN
FROM (
SELECT A.ID_LIST AS ID,
A.NAME,
A.DATE_CREATE AS DATECREATE,
A.DATE_UPDATE AS DATEUPDATE,
A.USER_ID AS USERID,
A.TYPE,
NVL(
B.CNT, 0
) CNT
FROM MAP_S_LIST_ARTS A
LEFT JOIN (
SELECT ID_LIST,
COUNT(*) CNT
FROM MAP_LIST_ARTS
GROUP BY ID_LIST
) B ON A.ID_LIST = B.ID_LIST
ORDER BY A.ID_LIST DESC
) BASEINFO
) FILTERED_ORDERED_RESULTS
ORDER BY CNT DESC
)
WHERE RN > (:PAGE * 5) AND RN <= (:PAGE + 1) * 5
What I get is that it first takes first 5 rows in another sorting (the default is by id) and then applies the sorting by cnt to them only. for example, if I fetch a page with 5 rows it will sort only among them though I have other pages. What can I do?