sprinkles icon indicating copy to clipboard operation
sprinkles copied to clipboard

Sql IN Statemenr

Open brescia123 opened this issue 11 years ago • 4 comments

How can I make a query with the IN statement?

brescia123 avatar Apr 12 '14 13:04 brescia123

Afaik there is no helper which auto-expands the params for you. But you could simply do this:

Query.many(YourModel.class, "SELECT * FROM YourModel WHERE column IN (?, ?)", "value1", "value2");

jdreesen avatar Apr 12 '14 14:04 jdreesen

Ok, but if I don't know the number of parameters I can't use this. I have to manually construct the sql query, right?

brescia123 avatar Apr 12 '14 14:04 brescia123

Yeah, something like this should do:

String[] params = new String[] {"value1", "value2", "value3", ...};

StringBuilder placeholder = new StringBuilder();
for (int i = 1; i <= params.length; i++) {
    placeholder.append("?");
    if (i < params.length) {
        placeholder.append(",");
    }
}

Query.many(YourModel.class, "SELECT * FROM YourModel WHERE column IN (" + placeholder.toString() + ")", params);

But maybe @emilsjolander comes with a better solution.

jdreesen avatar Apr 12 '14 15:04 jdreesen

@jdreesen is correct, this is the best solution currently. We should maybe look into adding a helper method for this. Of the top of my head i am thinking something a long the lines of

ArrayParam param = new ArrayParam(array)

param.commas() -> "?,?,?"
param.args() -> [obj1, obj2, obj3]

emilsjolander avatar Apr 13 '14 10:04 emilsjolander