复杂的sqLite查询LIKE子句

时间:2015-11-09 23:53:15

标签: android mysql database sqlite

我在Android中遇到sqLite查询问题。

基本上我想要的是:

SELECT * FROM table
WHERE column2 LIKE ?
OR column3 LIKE ?
AND column1 =?
GROUP BY column2
ORDER BY column2;

这是我的代码:

String query = "SELECT * FROM " +
    DBHelper.DB_SEARCH_TABLE + " WHERE " +
    DBHelper.DB_SEARCH_SEARCHVALUE + " LIKE ? OR " +
    DBHelper.DB_SEARCH_ARTIST + " LIKE ? AND " +
    DBHelper.DB_SEARCH_TYPE + " =? GROUP BY " +
    DBHelper.DB_SEARCH_SEARCHVALUE + " ORDER BY " +
    DBHelper.DB_SEARCH_SEARCHVALUE + ";";

cursor = mp3Database.rawQuery(query, new String[]{"%" + searchTerm + "%", "%" + searchTerm + "%", type});

查询类型的工作。它没有给出任何错误......但它也包括不属于我正在寻找的类型的行...(AND column1 =?)

LIKE条款的效果非常好......这只是问题的类型。

建议?

=========================

这是一个看似合理的查询吗?

SELECT * FROM Search 
WHERE (SearchValue LIKE ? OR Artist LIKE ?) OR 
(Artist LIKE ? AND Artist LIKE ?) AND
Type =? 
GROUP BY SearchValue
ORDER BY Artist , SearchValue;
 String query = "SELECT * FROM " +
                DBHelper.DB_SEARCH_TABLE + " WHERE (" +
                DBHelper.DB_SEARCH_SEARCHVALUE + " LIKE ? OR " +
                DBHelper.DB_SEARCH_ARTIST + " LIKE ?) OR (" +
                DBHelper.DB_SEARCH_ARTIST + " LIKE ? AND " +
                DBHelper.DB_SEARCH_ARTIST + " LIKE ?) AND " +
                DBHelper.DB_SEARCH_TYPE + " =? GROUP BY " +
                DBHelper.DB_SEARCH_SEARCHVALUE + " ORDER BY " +
                DBHelper.DB_SEARCH_ARTIST + " , " +
                DBHelper.DB_SEARCH_SEARCHVALUE + ";";


        cursor = mp3Database.rawQuery(query, new String[]{"%" + searchTerm + "%", "%" + searchTerm + "%", "%" + searchTerm + "%", "%" + search
                + "%", type});

1 个答案:

答案 0 :(得分:1)

您可能希望将where子句分组:WHERE (DBHelper.DB_SEARCH_SEARCHVALUE LIKE ? OR DBHelper.DB_SEARCH_ARTIST LIKE ?) AND DBHelper.DB_SEARCH_TYPE = ?

String query = "SELECT * FROM " +
    DBHelper.DB_SEARCH_TABLE + " WHERE (" +
    DBHelper.DB_SEARCH_SEARCHVALUE + " LIKE ? OR " +
    DBHelper.DB_SEARCH_ARTIST + " LIKE ?) AND " +
    DBHelper.DB_SEARCH_TYPE + " =? GROUP BY " +
    DBHelper.DB_SEARCH_SEARCHVALUE + " ORDER BY " +
    DBHelper.DB_SEARCH_SEARCHVALUE + ";";

cursor = mp3Database.rawQuery(query, new String[]{"%" + searchTerm + "%", "%" + searchTerm + "%", type});