我想在mysql数据库中查询值为IN
切片的表:
var qids []int
//fill qids dynamically
err = database.SQL.Select("es,
"SELECT * FROM quote WHERE qid IN $1", qids)
if err != nil {
log.Println(err)
}
但是我收到了这个错误:
sql: converting Exec argument #0's type: unsupported type []int, a slice
quotes []
我该如何解决这个问题?
答案 0 :(得分:9)
sqlx有一个很好的帮手:In()我们只需要准备带有args和Rebind的查询,如下所示:
var qids []int
// fills qids on query dynamically
query, args, err := sqlx.In("SELECT * FROM quote WHERE qid IN (?)", qids)
if err != nil {
log.Fatal(err)
}
// sqlx.In returns queries with the `?` bindvar, we can rebind it for our backend
//
query = database.SQL.Rebind(query) // database.SQL should be a *sqlx.DB
err = database.SQL.Select("es, query, args...)
if err != nil {
log.Fatal(err)
}
// or just in one line:
err = database.SQL.Select("es, database.SQL.Rebind(query), args...)
我还建议你看看这里:http://jmoiron.github.io/sqlx/有很多例子,包括 IN
答案 1 :(得分:0)
嘿因为[] int
试试这个
type Int64Array []int64
// Value returns the driver compatible value
func (a Int64Array) Value() (driver.Value, error) {
var strs []string
for _, i := range a {
strs = append(strs, strconv.FormatInt(i, 10))
}
return "{" + strings.Join(strs, ",") + "}", nil
}
然后将int64传递给查询
db.Queryx(“"SELECT * FROM quote WHERE qid IN $1", int64IDs)
了解详情,请查看here
答案 2 :(得分:-2)
标签表明您使用的是sqlx
。它在查询中有support for IN
。
所以你可以做到
var qids []int
//fill qids dynamically
rows, err = db.Query("es, "SELECT * FROM quote WHERE qid IN ($1)", qids)
if err != nil {
log.Println(err)
}
// scan the rows