我正在尝试运行如下查询,但只有第一个id值返回:-
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
我已经完成以下工作:
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"
在获取数据时,它仅返回值“ 1”,并且忽略与他一起传递的所有其他ID,即'2', '3', '4', '5', '6', '7', '9', '11', '13', '14', '15', '17'
。
如何正确通过?
我正在使用go-sql-driver/mysql
。
常问问题 :
aID
确实包含所有这些数字作为字符串,并且
table具有上面提供的所有可用行id
。
table
是从那里id
获取并附加到那里的,并且另存有aID
记录的记录是从语句中获取的。id
aID
in
table2
谢谢
您可以执行以下操作:
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...)
请注意,如果asID
len == 0,您将想设防。
如果要传递任何其他参数,则必须将它们添加到args
切片中。
还要注意的是,您应该显式命名所需的列,这样可以保证您在正确的列中扫描到正确的字段。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句