Golang使用数组值在数据库查询中过滤记录。

huangapple go评论82阅读模式
英文:

Golang use array values in db query to filter records

问题

我有一个 int64 值的数组列表:

ids = [{1} {2} {3}]

我想在数据库查询中使用上述数组来筛选出 ID 不在上述 ids 中的记录。

SELECT * from table where id not in (1,2,3);

我尝试了很多方法,但无法生成查询字符串。

英文:

I have list of array int64 values

ids = [{1} {2} {3}]

I want to use the above array in db query to filter out the records where ID is not in above ids.

SELECT * from table where id not in (1,2,3);

I tried many ways to do but failing to make the query string.

答案1

得分: 1

我已经创建了一个示例场景,如下所示:

func main() {
    ids := []int{1, 2, 3}

    var tmp []string

    for _, v := range ids {
        tmp = append(tmp, fmt.Sprint(v))
    }

    query := "SELECT * from table where id not in (" + strings.Join(tmp, ",") + ")"
    fmt.Println(query)

}

或者你可以在Go Playground上运行它:链接

英文:

I have created a sample scenario as follows :

func main() {
	ids := []int{1, 2, 3}

	var tmp []string

	for _, v := range ids {
		tmp = append(tmp, fmt.Sprint(v))
	}

	query := "SELECT * from table where id not in (" + strings.Join(tmp, ",") + ")"
	fmt.Println(query)

}

OR

You can run it in go playground link

huangapple
  • 本文由 发表于 2021年12月6日 16:29:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/70242652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定