0

我有一个 MySQL 数据库(版本 5.2 CE),我有一个表,我想根据用户给出的 WHERE 条件(来自数组列表)将其过滤到另一个表中。我想针对用户选择的拆分对这个新表执行计数查询。例如,来自 TableName WHERE 的 COUNT(*) [userConditions like gender=male and gender=female, etc]。用户可以提供多个 WHERE 条件,但 COUNT 查询一次只能采用一个条件。因此,我将我的方法(执行此查询)设为一个数组,以根据用户选择的条件数量返回多个查询,然后在 for 循环中执行每个查询。但是,这似乎以两种方式给了我编译错误:i)我在 String[] 方法中返回构建字符串的方式和 ii)我执行 COUNT 查询的方式。这些问题的代码:

private String countQuery;

public SetupSubsamplePopulation(UserSelectedSplit split) {

    this.split = split;
    // connect to the database
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull","root", "sharadha_1992");

        String buildSelectQuery = buildSelectQueryForCode();
        String getRowsFromTable = getNumberOfRows();
        stmt = connection.createStatement();
        rows = stmt.executeUpdate(buildSelectQuery);
        ResultSet rs = stmt.executeQuery(getRowsFromTable);

        for (int i=0; i<getCountOfWhereCondition().length; i++){
            //where I get the executeQuery error
            ResultSet rs1= stmt.execute(getCountOfWhereCondition());
            while (rs1.next()){
                rowsCount= rs.getRow();
                rows_count++;
            }
        }
        while (rs.next()) {
            rows = rs.getRow();
            rows_inserted++;
        }

        System.out.println(rows_inserted);
        System.out.println(rows_count);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

返回 COUNT 个查询数组的方法:

public String[] getCountOfWhereCondition() {
    countQuery="SELECT COUNT (*) FROM (SELECT * from mygrist_samples.subsample_population WHERE ";

    for (int i = 0; i < split.getSplitConditions().size(); i++) {

        String getCorrespondingCodeFromDatabase = split.getSplitConditions().get(i).getCode();
        getCorrespondingCodeFromDatabase = getCorrespondingCodeFromDatabase.replaceAll("-", "_");

        Enumerations enum1 = new Enumerations();

        String getCorrespondingRelationshipOperator = enum1.getOperator(split.getSplitConditions().get(i).getRelationship());

        countQuery+=getCorrespondingCodeFromDatabase + " " + getCorrespondingRelationshipOperator + " '" + split.getSplitConditions().get(i).getAnswer() + "'";
    }
    countQuery+=")";

    System.out.println(countQuery);
    //error which doesn't allow me to return a string
    return countQuery;


}

有人可以告诉我如何明智地实施吗?非常感谢你。

4

1 回答 1

1

我认为您想要条件聚合而不是where

select count(*)
from  mygrist_samples.subsample_population
WHERE XXX

是相同的:

select sum(case when XXX then 1 else 0 end) as cnt1
from mygrist_samples.subsample_population

现在您可以在一次调用中添加多个条件:

select sum(case when XXX then 1 else 0 end) as cnt1,
       sum(case when yyy then 1 else 0 end) as cnt1
from  mygrist_samples.subsample_population
于 2013-04-04T19:44:30.880 回答