1

I want to provide a query to my database that will search if a string exists in Column1 OR in Column2 AND only display it if another String value exists in Column3.

This my working code for searching in 2 columns :

mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                 KEY_TIME, KEY_TITLE, KEY_COLOR, KEY_BODY}, 
                 KEY_BODY + " like '%" + inputText + "%' OR " + KEY_TITLE + " like '%" + inputText + "%'" , null,
                 null, null, KEY_TIME + " DESC", null);

I cannot figure out how to add the third column to the Search though.

I tried this :

mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                     KEY_TIME, KEY_TITLE, KEY_COLOR, KEY_BODY}, 
                     KEY_BODY + " like '%" + inputText + "%' OR " + KEY_TITLE + " like '%" + inputText + "%' AND " + KEY_COLOR + "like '%" + colorvalue + "%'" , null,
                     null, null, KEY_TIME + " DESC", null);

but the AND only applies to the "TITLE" column not both. I've searched around the web but i couldn't figure it out.

Your help would be appreciated!

4

2 回答 2

2

为此,您需要使用括号。

mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                 KEY_TIME, KEY_TITLE, KEY_COLOR, KEY_BODY}, 
                 "(" + KEY_BODY + " like '%" + inputText + "%' OR " + KEY_TITLE + " like '%" + inputText + "%') AND (" + KEY_COLOR + " like '%" + colorvalue + "%')" , null,
                 null, null, KEY_TIME + " DESC", null);

希望这可以帮助。

于 2013-05-10T13:01:10.177 回答
2

我想向我的数据库提供一个查询,该查询将搜索 Column1 中是否存在字符串或 Column2 中是否存在字符串,并且仅在 Column3 中存在另一个字符串值时才显示它。

所以这不应该太棘手。您需要在语句中添加回溯(用于首先包装或条件),然后一切都应该正常工作。

例子:

String query = "select * from SomeTable
                where (column1 like ? and column2 like ?) and column3 like ?";
String[] params = {"%" + param1 + "%", "%" + param2 + "%", "%" + param3 + "%"};
Cursor c = db.rawQuery(query, params);

让我知道。

注意:我真的不喜欢您的“硬编码”方法。我建议您使用参数化的 statemets,它比经典的“硬编码”statemets更易于阅读且更安全。不要忘记有SQL注射的可能危险。

于 2013-05-10T13:07:40.600 回答