A
A
Anatoly2015-09-21 20:18:05
Android
Anatoly, 2015-09-21 20:18:05

How to make a SQLite query with a condition for different fields?

android studio. I have 4 fields in the program for entering ingredients, I want that no matter which field you enter the ingredient in, the search is carried out in all fields of the table. (in the table, in addition to id, there are 4 fields with ingredients). 4 fields are needed for searching, let's say 2,3 or 4 ingredients. That is, if we filled in all 4 fields, then only the recipe that contains all these 4 ingredients should be selected, but regardless of their order in the fields for this dish.
The query I was hoping to do is:

String sqlQuery = "SELECT * "
                + "from dishtab "
                + "inner join ingrtab "
                + "on dishtab._id = ingrtab._id "
                + "where ingrtab.ingr_1 = ? OR ingr_2 = ? OR ingr_3 = ? OR ingr_4 = ?";
        c = mDB.rawQuery(sqlQuery, new String[] {ingr1, ingr2, ingr3, ingr4} );

This request does not suit me, as it searches for specific fields. Tell me how to write a query that will search for all fields, for any 4 input data? That is, as I understand it, instead of each question "?" all four variables ingr1, ingr2, ingr3, ingr4 should be substituted instead of one for each question.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anatoly, 2015-09-23
@TonyWrong

Thanks to everyone who commented , I wouldn't have figured it out without you! Here is a query that finally does what I need:
But there is one important note, this code searches by the number of variables from 1 to 3, and the fourth variable must be a dummy (in my case, the text value "null") other than that, in each line, the fourth ingredient field must be identical to the dummy, then everything works !

D
Dmitry Kovalsky, 2015-09-21
@dmitryKovalskiy

If I understood correctly, then you can create 4 sql variables and write something like

(@ingr1 is NULL OR [email protected])OR (@ingr2 is NULL OR [email protected]) OR (@ingr3 is NULL OR [email protected]) OR (@ingr4 is NULL OR [email protected])

M
Max, 2015-09-21
@MaxDukov

maybe so?

where ingrtab.ingr_1 IN (?,?,?,?) OR ingr_2 = (?,?,?,?) OR ingr_3 = (?,?,?,?) OR ingr_4 = (?,?,?,?)

N
nozzy, 2015-09-22
@nozzy

where ingrtab.ingr_1 in (?,?,?,?)
or ingrtab.ingr_2 in (?,?,?,?)
or ingrtab.ingr_3 in (?,?,?,?)
or ingrtab.ingr_4 in (?, ?,?,?)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question