Sqlite按案例排序

时间:2015-07-08 16:44:43

标签: android sqlite

我正在尝试搜索联系人列表,并按优先顺序向用户显示列表。订单是display_name,电话,电子邮件和地址。我已经回顾了Stackoverflow和sqlite.org上的几个例子但没有运气。

如果用户搜索“john”,那么display_name中所有带“john”的联系人将首先按降序排列,然后是可能位于Johnson City等的联系人。搜索不区分大小写且数量有限到50行。

    String[] projection = {
        DTab._id.toString(),
        DTab.contact_id.toString(),
        DTab.display_name.toString(),
        DTab.phone.toString(),
        DTab.email.toString(),
        DTab.kv.toString(),
        DTab.address.toString(),
};

String where = ""
    +"("+DTab.display_name+" LIKE ?) OR "
    +"("+DTab.phone+" LIKE ?) OR "
    +"("+DTab.email+" LIKE ?) OR "
    +"("+DTab.address+" LIKE ?)";
String[] args = new String[]{
        "%" + search + "%",
        "%" + search + "%",
        "%" + search + "%",
        "%" + search + "%",
};

String orderBy =
        "CASE "
        +"WHEN "+DTab.display_name+" LIKE ? != '' THEN 1 "
        +"WHEN "+DTab.phone       +" LIKE ? != '' THEN 2 "
        +"WHEN "+DTab.email       +" LIKE ? != '' THEN 3 "
        +"ELSE 4 "
+"END LIMIT 50";

Cursor c = detail_db.query(DETAIL_TABLE, projection, where, args, null, null, orderBy);

排序顺序不正确,就好像忽略了定义中的顺序一样。我得到一些匹配display_name的记录,后跟匹配电子邮件的记录,后跟更多display_name记录。关于如何调试它的见解或建议值得赞赏。

2 个答案:

答案 0 :(得分:1)

从订单条款中删除!= ''比较:

String orderBy = "CASE WHEN " + DTab.display_name + " LIKE ? THEN 1 "
        + "WHEN " + DTab.phone + " LIKE ? THEN 2 "
        + "WHEN " + DTab.email + " LIKE ? THEN 3 "
        + "ELSE 4 END ASC "
        + "LIMIT 50";

答案 1 :(得分:0)

您有七个参数(?),但args数组中只有四个值,因此最后三个参数的值为NULL

您可以使用parameter numbers重复使用参数值:

String where = ""
    +"("+DTab.display_name+" LIKE ?1) OR "
    +"("+DTab.phone       +" LIKE ?2) OR "
    +"("+DTab.email       +" LIKE ?3) OR "
    +"("+DTab.address     +" LIKE ?4)";
String orderBy =
    "CASE "
    +"WHEN "+DTab.display_name+" LIKE ?1 THEN 1 "
    +"WHEN "+DTab.phone       +" LIKE ?2 THEN 2 "
    +"WHEN "+DTab.email       +" LIKE ?3 THEN 3 "
    ...

(正如Karakuri所说,!= ''没有意义。)