如何使用sqlx查询mysql IN一个切片?

How to use sqlx to query mysql IN a slice?

我想在 mysql 数据库中查询 table 的值 IN 切片:

var qids []int
//fill qids dynamically
err = database.SQL.Select(&quotes,
    "SELECT * FROM quote WHERE qid IN ", qids)
if err != nil {
    log.Println(err)
}

但是我得到这个错误:

sql: converting Exec argument #0's type: unsupported type []int, a slice
quotes []

我该如何解决这个问题?

嘿,这是因为 []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给query

db.Queryx("SELECT * FROM quote WHERE qid IN ", int64IDs)

查看更多详情here

标签表明您正在使用 sqlx。它有 support for IN 个查询。

所以你可以做到

var qids []int
//fill qids dynamically
rows, err = db.Query(&quotes, "SELECT * FROM quote WHERE qid IN ()", qids)
if err != nil {
    log.Println(err)
}
// scan the rows

sqlx 对此有一个很好的帮助:In() 我们只需要通过获取 args 和重新绑定来准备查询,就像这样:

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(&quotes, query, args...)
if err != nil {
    log.Fatal(err)
}

// or just in one line:

err = database.SQL.Select(&quotes, database.SQL.Rebind(query), args...)

此外,我建议您看一下这里:http://jmoiron.github.io/sqlx/ 有很多示例,包括 IN