I have a cars sqlite database with one table that has 3 columns: year, make and model. With the below query, I can search on a single phrase like “ford” and it will display all ford results, or “1964” and I’ll get all cars from that year. But “1964 ford” returns “no results found” – or null. How can the query be modified so that I can enter search terms from all 3 columns like “1964 ford mustang”? Yes, I know there’s no such thing as a 1964 ford mustang, it’s 1964 and a half. But there is a row for a 1964 ford mustang in my DB, so let’s use “1966 ford mustang” as the example.
public Cursor searchDB(String query) {
return db.query(true, DB_TABLE, new String[] { KEY_ROWID, KEY_YEAR, KEY_MAKE,
KEY_MODEL }, KEY_YEAR + " LIKE" + "'%" + query + "%' OR " + KEY_MAKE +
" LIKE" + "'%" + query + "%' OR " + KEY_MODEL + " LIKE" + "'%" + query + "%'",
null, null, null, null, null);
}
I’ve tried using AND in place of + but that crashes. I’m using android 2.2.
The reason it’s not working is your
column LIKE %query%statements. That’s saying that the value has to contain your query exactly with any number of characters on either end. So"1964" LIKE "%1964 mustang%"would fail but"1964 mustang" LIKE "%1964%"would give you the proper result.If you split your query string by spaces and query each column against each split string, that would likely give you the results you’re looking for.
UPDATE: Snippet for splitting the string and forming the query.