使用where in子句的mysql查询中的golang切片 [英] golang slice in mysql query with where in clause

查看:73
本文介绍了使用where in子句的mysql查询中的golang切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试像下面那样运行查询,但是只有第一个id值返回:-

I am trying to run query like below , but only first id value returns :-

select * from `table` where table`.`id` in ('1', '2', '3', '4', '5', '6', '7', '9', '11', '13', '14', '15', '17') and `table`.`deleted_at` is null

我已经完成以下操作:-

I have done following :-

var aID = make([]string, 0)
var in india // india is struct

for rows.Next() {
    cook := rows.Scan(&in.ID)

    aID = append(aID, strconv.Itoa(in.ID))
}

asID = strings.Join(aID, ",")

anotherRow,err := db.Query("SELECT * from table2 where id in (?)", asID)
if err != nil { fmt.Printf("Error: ", err) }
// ... Other line follows up with "for anotherRow.Next() and fetching"

在获取数据时,它仅返回值"1",并忽略与他一起传递的所有其他ID,即'2','3','4','5','6','7','9','11','13','14','15','17'.

While fetching data, it only returns value of "1" and ignores all other ID passed on with him, which are '2', '3', '4', '5', '6', '7', '9', '11', '13', '14', '15', '17'.

我如何正确通过?

我正在使用 go-sql-driver/mysql .

常见问题解答:

  1. aID 确实包含所有这些数字,例如字符串和

  1. aID does contain all those numbers as string and

表具有在 id 上方提供的所有可用行.

table has all the rows available with provided above id.

是从其中获取 id 并将其附加到 aID 和具有 id 的另一条记录的地方使用 in 语句中的 in 语句从 table2 中获取存储在 aID 中的内容.

table is from where id is fetched and appended to aID and another records with id stored in aID are fetched with in statement from table2.

谢谢

推荐答案

您可以执行以下操作:

args := make([]interface{}, len(asID))
for i, id := range asID {
    args[i] = id
}
stmt := `SELECT * from table2 where id in (?` + strings.Repeat(",?", len(args)-1) + `)`
anotherRow, err := db.Query(stmt, args...)

请注意,如果 asID 可以具有len == 0,您将要加倍警惕.

Just note you will want to put in a guard if asID can ever have len == 0.

如果要传递任何其他参数,则必须将它们添加到 args 切片中.

If you have any other arguments to pass in, you'll have to add them to the args slice.

还要注意,您应该显式命名所需的列,这样可以保证您在正确的列中扫描到正确的字段.

Also to note, you should explicitly name the columns you want so you can guarantee you are scanning in the correct columns to the correct fields.

这篇关于使用where in子句的mysql查询中的golang切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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