【问题标题】:How to do this query with a complex where statement in Sqlite in Android?如何在 Android 的 Sqlite 中使用复杂的 where 语句执行此查询?
【发布时间】:2012-05-25 11:22:57
【问题描述】:

我有一个包含 100 列或更多列的表,这些列的值可能是“yes”或“no”。

我想根据用户的请求(复选框值表单)进行选择,以提取所有值为“yes”的行。所以一个例子可能是:

-用户选择了 checkbox1 checkbox4 和 checkbox7 其他的都没有被选中。

查询可能是:

从表中选择名称,其中 (col1 = yes or col4 = yes or col7 = yes) A​​ND (col2= no and col3 = no and all other columns are set to no)

如何在 android 查询中实现这一点?顺便说一下,我发现这个实现不是很优雅,有人可以建议我用其他实现来实现这个目标吗?

【问题讨论】:

    标签: android sqlite select where


    【解决方案1】:

    这是固定代码。它包含一些测试代码。

            int numColumns = 10;
            boolean[] answers = new boolean[numColumns];
            String[] colNames = new String[numColumns];
            for(int i = 0; i < colNames.length; i++) {
                answers[i] = Math.random() > 0.5;
                colNames[i] = String.format("Col%d", i);
            }
            //-----------LOGIC STARTS HERE----------------
            // use a loop
            StringBuilder yesColumns = new StringBuilder();
            StringBuilder noColumns = new StringBuilder();
            for(int i = 0; i < answers.length; i++) {
                if(answers[i]) {
                    if(yesColumns.length() > 0)
                        yesColumns.append(" OR ");
    
                    yesColumns.append(colNames[i]).append("='yes'");
                }
                else {
                    if(noColumns.length() > 0)
                        noColumns.append(" AND ");
                    noColumns.append(colNames[i]).append("='no'");
                }
            }
    
            String yesCondition = yesColumns.toString();
            String noCondition = noColumns.toString();
            String query = String.format("select name from table where (%s) AND (%s)",
                                         yesCondition,
                                         noCondition);
            System.out.println(query);
            // SQLiteDatabase db;
            // Cursor cursor = db.rawQuery(query, null);
    

    【讨论】:

    • 首先感谢您的请求。问题是选择应该分为两部分:用户打开复选框(是),该值将使用“或”关键字进入查询的第一部分,未选中(否)将进入和部分:从表中选择名称 where (col1 = yes or col4 = yes or col7 = yes) A​​ND (col2= no and col3 = no and all other columns are set to no)
    • 哦,对不起,完全错过了or 条件,让我来解决。
    • 我修好了,如果有问题,请知道。 :P
    • 您好 st0le,您能告诉我我必须包含哪些库吗?
    • @user1417084,我认为您不需要添加任何库,我使用的所有内容都是 android 原生的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    相关资源
    最近更新 更多