0

I have a really simple mysql table, with 3 columns, A, B and C.

A and B are keys.

I have a GO app and I'm trying to retrieve data from db. With other queries works like a charm, but with this one it doesn't:

aParam := "aValue"
bParam := "3,4,6,9"
stmt, err := o.database.Prepare("SELECT * FROM tableX WHERE `A`= ? AND `B` IN ( ? )")
defer stmt.Close()
rows, err := stmt.Query(aParam, bParam)
for rows.Next() {
...
}

If I replace the second ? for the values, it works perfect:

stmt, err := o.database.Prepare("SELECT * FROM tableX WHERE `A`= ? AND `B` IN ( 3,4,6,9 )")

I also tried with this (it doesn't work):

stmt, err := o.database.Prepare("SELECT * FROM tableX WHERE `A`= ? AND `B` IN ( " + bParam +" )")

Any idea?

1
  • What DB driver are you using? Popular Go DB drivers often don't support IN queries very well. Commented Aug 19, 2015 at 15:24

1 Answer 1

2

The issue is that the single ? is not expanded into the SELECT statement (like a string replace), but as a single string value 3,4,5,6

You need to expand each value of the IN clause as such:

params := []interface{} { "aValue", 3, 4, 6, 9 }
stmt, err := o.database.Prepare("SELECT * FROM tableX WHERE `A`= ? AND `B` IN ( ?, ?, ?, ? )")
defer stmt.Close()
rows, err := stmt.Query(params...)

To make your life easier, you can use a package like sqlx, which has better support for parameterized IN queries

Sign up to request clarification or add additional context in comments.

3 Comments

another option would be to populate temporary table to keep 'IN' list and then use this table in the query (either join or IN subquery). This way you are not bounded too much handling varying size of IN list.
ok, just another question, here: params := []interface{} { "aValue", 3, 4, 6, 9 } I need to add dynamically those values, I not even know how many they are going to be
you would need to generate a string of ?'s for the IN clause matching the number of IDs you need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.