2016-11-12 45 views
3

我想查詢表在MySQL數據庫中值IN片:如何使用sqlx在切片中查詢mysql?

var qids []int 
//fill qids dynamically 
err = database.SQL.Select(&quotes, 
    "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

可能重複[Go和IN子句在P ostgres](http://stackoverflow.com/questions/38036752/go-and-in-clause-in-postgres);和[Golang MySQL使用IN運算符查詢未定義的args數量](http://stackoverflow.com/questions/39223856/golang-mysql-querying-undefined-amount-of-args-using-in-operator)。 – icza

+2

@icza我不這麼認爲。這個功能只能在'sqlx'中使用。 – TheHippo

回答

4

SQLX有一個偉大的助手爲:In()我們只需要準備查詢到的指定參數和重新綁定,就像這樣:

var qids []int 
// fill qids dynamically 

query, args, err := sqlx.In("SELECT * FROM quote WHERE qid IN (?)", qids) 
if err != nil { 
    log.Println(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.Println(err) 
} 

此外,我建議你看看這裏:http://jmoiron.github.io/sqlx/有很多的例子,包括IN

+1

我希望成爲更復雜的東西,但仍然有效。謝謝。 – Karlom

0

嘿它,因爲[]詮釋
試試這個

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

0

的標籤表明,您正在使用sqlx。它在查詢中有support for IN

所以,你可以做

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

是的我使用'sqlx',但不知道爲什麼我仍然得到相同的錯誤。 – Karlom