gpt4 book ai didi

sql - Go模板连接 slice 中的查询

转载 作者:IT王子 更新时间:2023-10-29 02:05:34 27 4
gpt4 key购买 nike

我想将我的 SQL 查询与 UNION ALL 和 golang http://golang.org/pkg/text/template/ 连接起来

例如,我有:

var slice1 = []string{"2014-01-01", "2014-01-02", "2014-01-03"}
var slice2 = []string{"20140101", "20140102", "20140103"}

并查询:

select {{.date}} as date, itemid, price
from orderhistory_t{{datetag}}

并使用模板创建如下查询:

select '2014-01-01' as date, itemid, price
from orderhistory_t20140101

union all

select '2014-01-02' as date, itemid, price
from orderhistory_t20140102

union all

select '2014-01-03' as date, itemid, price
from orderhistory_t20140103

如何循环遍历 Golang 的 slice 并将它们放入 sql 模板中?

提前致谢!

最佳答案

我认为模板不是完成这项工作的合适工具。只需创建查询字符串并在此处加入它即可:

http://play.golang.org/p/mM0mMfBZFK

package main

import (
"fmt"
"strings"
)

var slice1 = []string{"2014-01-01", "2014-01-02", "2014-01-03"}
var slice2 = []string{"20140101", "20140102", "20140103"}

func main() {
var parts []string
for i := 0; i < len(slice1); i++ {
parts = append(parts, fmt.Sprintf("select %q as date, itemid, price from orderhistory_t%s", slice1[i], slice2[i]))
}
fmt.Println(strings.Join(parts, " union all "))
}

输出:

select "2014-01-01" as date, itemid, price from orderhistory_t20140101 union all select "2014-01-02" as date, itemid, price from orderhistory_t20140102 union all select "2014-01-03" as date, itemid, price from orderhistory_t20140103

关于sql - Go模板连接 slice 中的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com