如何使用Golang在SQL中执行IN查找? [英] How to execute an IN lookup in SQL using Golang?

查看:136
本文介绍了如何使用Golang在SQL中执行IN查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go在这个SQL查询中为第二个参数需要什么。
我试图在postgres中使用 IN 查找。

  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); 


解决方案

查询只需要varargs来替换sql中的参数
所以,在你的例子中,你只需要做
$ b $ $ $ $ $ $ $ $ $ $行,err:= stmt.Query(10)

说,这和你的第二个例子是动态的,那么你会这样做。 b
$ b

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

如果你有IN部分的变量参数,你可以做(​​播放

 包主
$ b导入fmt
导入字符串

func main() {
stuff:= [] interface {} {this,that,otherthing}
sql:=select * from foo where id =?and name in(?+ strings 。重复(,?,len(stuff)-1)+)
fmt.Println(SQL:,sql)
args:= [] interface {} {10}
args = append(args,stuff ...)
fakeExec(args ...)
//这也适用,但我认为人们很难阅读
// fakeExec(append ([] interface {} {10},stuff ...)...)
}

func fakeExec(args ... interface {}){
fmt。 Println(Got:,args)
}


What does Go want for the second param in this SQL query. I am trying to use the IN lookup in postgres.

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

What I really want:

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

解决方案

Query just takes varargs to replace the params in your sql so, in your example, you would just do

rows, err := stmt.Query(10)

say, this and that of your second example were dynamic, then you'd do

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

If you have variable args for the "IN" part, you can do (play)

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)
}

这篇关于如何使用Golang在SQL中执行IN查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆