Sfoglia il codice sorgente

修复分页优化distinct搭配orderBy处理错误.

https://github.com/baomidou/mybatis-plus/issues/6105
nieqiurong 1 anno fa
parent
commit
74b5d38577

+ 6 - 8
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/inner/PaginationInnerInterceptor.java

@@ -267,13 +267,6 @@ public class PaginationInnerInterceptor implements InnerInterceptor {
                 return lowLevelCountSql(sql);
             }
             PlainSelect plainSelect = (PlainSelect) select;
-            Distinct distinct = plainSelect.getDistinct();
-            GroupByElement groupBy = plainSelect.getGroupBy();
-
-            // 包含 distinct、groupBy 不优化
-            if (null != distinct || null != groupBy) {
-                return lowLevelCountSql(select.toString());
-            }
 
             // 优化 order by 在非分组情况下
             List<OrderByElement> orderBy = plainSelect.getOrderByElements();
@@ -291,7 +284,12 @@ public class PaginationInnerInterceptor implements InnerInterceptor {
                     plainSelect.setOrderByElements(null);
                 }
             }
-
+            Distinct distinct = plainSelect.getDistinct();
+            GroupByElement groupBy = plainSelect.getGroupBy();
+            // 包含 distinct、groupBy 不优化
+            if (null != distinct || null != groupBy) {
+                return lowLevelCountSql(select.toString());
+            }
             //#95 Github, selectItems contains #{} ${}, which will be translated to ?, and it may be in a function: power(#{myInt},2)
             for (SelectItem item : plainSelect.getSelectItems()) {
                 if (item.toString().contains(StringPool.QUESTION_MARK)) {

+ 4 - 0
mybatis-plus-extension/src/test/java/com/baomidou/mybatisplus/test/extension/plugins/inner/PaginationInnerInterceptorTest.java

@@ -31,6 +31,10 @@ class PaginationInnerInterceptorTest {
 
         assertsCountSql("select * from user u LEFT JOIN role r ON r.id = u.role_id LEFT JOIN permission p on p.id = u.per_id WHERE u.xx = ?",
             "SELECT COUNT(*) AS total FROM user u WHERE u.xx = ?");
+
+        assertsCountSql("select distinct id from table order by id", "SELECT COUNT(*) FROM (SELECT DISTINCT id FROM table) TOTAL");
+
+        assertsCountSql("select distinct id from table", "SELECT COUNT(*) FROM (SELECT DISTINCT id FROM table) TOTAL");
     }
 
     @Test