小编典典

如何使用Golang在SQL中执行IN查找?

go

Go对于此SQL查询中的第二个参数想要什么。我正在尝试IN在postgres中使用查找。

stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id= $1 AND other_field IN $2")
rows, err := stmt.Query(10, ???)

我真正想要的是:

SELECT * FROM awesome_table WHERE id=10 AND other_field IN (this, that);

阅读 967

收藏
2020-07-02

共1个答案

小编典典

查询只是使用varargs来替换sql中的参数,因此,在您的示例中,您只需要执行

rows, err := stmt.Query(10)

例如,这个和第二个示例的内容是动态的,那么您将

stmt, err := db.Prepare("SELECT * FROM awesome_table WHERE id=$1 AND other_field IN ($2, $3)")
rows, err := stmt.Query(10,"this","that")

如果“ IN”部分具有可变的args,则可以执行(播放

package main

import "fmt"
import "strings"

func main() {
    stuff := []interface{}{"this", "that", "otherthing"}
    sql := "select * from foo where id=? and name in (?" + strings.Repeat(",?", len(stuff)-1) + ")"
    fmt.Println("SQL:", sql)
    args := []interface{}{10}
    args = append(args, stuff...)
    fakeExec(args...)
    // This also works, but I think it's harder for folks to read
    //fakeExec(append([]interface{}{10},stuff...)...)
}

func fakeExec(args ...interface{}) {
    fmt.Println("Got:", args)
}
2020-07-02