Merge pull request #1062 from wenshao/master

PagerUtils support count(distinct)
This commit is contained in:
wenshao
2016-01-26 11:38:36 +08:00
2 changed files with 21 additions and 3 deletions
@@ -20,8 +20,10 @@ import java.util.List;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLOrderBy;
import com.alibaba.druid.sql.ast.SQLOver;
import com.alibaba.druid.sql.ast.SQLSetQuantifier;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLAggregateExpr;
import com.alibaba.druid.sql.ast.expr.SQLAggregateOption;
import com.alibaba.druid.sql.ast.expr.SQLAllColumnExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator;
@@ -334,9 +336,18 @@ public class PagerUtils {
if (queryBlock.getGroupBy() != null && queryBlock.getGroupBy().getItems().size() > 0) {
return createCountUseSubQuery(select, dbType);
}
queryBlock.getSelectList().clear();
queryBlock.getSelectList().add(countItem);
int option = queryBlock.getDistionOption();
if (option == SQLSetQuantifier.DISTINCT && queryBlock.getSelectList().size() == 1) {
SQLSelectItem firstItem = queryBlock.getSelectList().get(0);
SQLAggregateExpr exp = new SQLAggregateExpr("COUNT", SQLAggregateOption.DISTINCT);
exp.getArguments().add(firstItem.getExpr());
firstItem.setExpr(exp);
queryBlock.setDistionOption(0);
} else {
queryBlock.getSelectList().clear();
queryBlock.getSelectList().add(countItem);
}
return SQLUtils.toSQLString(select, dbType);
} else if (query instanceof SQLUnionQuery) {
return createCountUseSubQuery(select, dbType);
@@ -29,6 +29,13 @@ public class PagerUtilsTest_Count_MySql_0 extends TestCase {
Assert.assertEquals("SELECT COUNT(*)\n" + //
"FROM t", result);
}
public void test_mysql_3() throws Exception {
String sql = "select distinct id from t order by id";
String result = PagerUtils.count(sql, JdbcConstants.MYSQL);
Assert.assertEquals("SELECT COUNT(DISTINCT id)\n" + //
"FROM t", result);
}
public void test_mysql_group_0() throws Exception {
String sql = "select type, count(*) from t group by type";