英文:
Go template to concatenate queries from the slice
问题
我想将我的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的切片并将它们放入SQL模板中?
提前谢谢!
英文:
I want to concatenate my SQL query with UNION ALL
and golang http://golang.org/pkg/text/template/
For example, I have:
var slice1 = []string{"2014-01-01", "2014-01-02", "2014-01-03"}
var slice2 = []string{"20140101", "20140102", "20140103"}
And query:
select {{.date}} as date, itemid, price
from orderhistory_t{{datetag}}
And using the template I want to create the query like the following:
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
How do I loop through the slice of Golang and put them in the sql template?
Thank you in advance!
答案1
得分: 2
我不认为模板是这个工作的正确工具。只需创建查询字符串并在此处连接即可:
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
英文:
I don't think template is the right tool for the job. Just create the query string and join it here is how:
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 "))
}
output:
> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论