I am running the below query, but only get the first id value:-
select * from `table` where table`.`id` in ('1', '2', '3', '4', '5', '6', '7', '9', '11', '13', '14', '15', '17') and `table`.`deleted_at` is null
I have done the following:-
var aID = make([]string, 0)
var in India // india is struct
for rows.Next() {
cook := rows.Scan(&in.ID)
aID = append(aID, strconv.Itoa(in.ID))
}
asID = strings.Join(aID, ",")
anotherRow,err := db.Query("SELECT * from table2 where id in (?)", asID)
if err != nil { fmt.Printf("Error: ", err) }
// ... Other line follows up with "for anotherRow.Next() and fetching"
While fetching data, it only returns value of "1" and ignores all other ID passed to it, which are '2', '3', '4', '5', '6', '7', '9', '11', '13', '14', '15', '17'
.
How can I pass it correctly?
I am using go-sql-driver/mysql
.
FAQ :
aID
does contain all those numbers as string and
table has all the rows available with provided above id
.
table
is from where id
is fetched and appended to aID
and another record with id
stored in aID
are fetched with in
statement from table2
.
Thanks
You can do something like this:
args := make([]interface{}, len(asID))
for i, id := range asID {
args[i] = id
}
stmt := `SELECT * from table2 where id in (?` + strings.Repeat(",?", len(args)-1) + `)`
anotherRow, err := db.Query(stmt, args...)
Just note you will want to put in a guard if asID
can ever have len == 0.
If you have any other arguments to pass in, you'll have to add them to the args
slice.
Also to note, you should explicitly name the columns you want so you can guarantee you are scanning in the correct columns to the correct fields.
Try
q,args,err := sqlx.In("SELECT * FROM table2 WHERE id IN(?);", asID) //creates the query string and arguments
rows, err := db.Query(q,args...)
You could also use the Masterminds/squirrel package:
import sq "github.com/Masterminds/squirrel"
...
users := sq.Select("*").From("table2")
active := users.Where(sq.Eq{"id":[]string{"1","2","3"}})
sql, args, err := active.ToSql()
Which will do the in clause
automatically when using sq.Eq struct with a slice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With