用户可以根据许多不同的标准请求产品价格,这将导致它可能访问表中的不同列。我正在遍历请求的产品并构建一堆查询,但遇到了一些麻烦。
一个一个地运行它们并组合结果比将它们联合起来需要更长的时间。因此,我尝试构建如下查询,它有效且速度快,但现在容易受到注入的影响。
没有联盟有没有更好的方法来做到这一点?或者有没有一种简单的方法可以参数化这样的动态查询?
var fullQuery string
var counter int
for i, d:= range dataMap{
if counter != 0 {
fullQuery = fullQuery + " UNION "
}
var records string
for _, p := range d{
records = records + `'` + string(p) + `',`
}
recordLength:= len(records)
if recordLength> 0 && records [recordLength-1] == ',' {
records = records[:recordLength-1]
}
counter++
fullQuery = fullQuery + fmt.Sprintf(`
SELECT
price_`+fmt.Sprint(p.type)+` as price,
FROM products
WHERE products.id in (%s) and products.store= %s
`, records, p.store)
}
err := sqlx.Select(db, &dataStruct, fullQuery)
所以,在某些情况下,我可能会有以下查询:
SELECT
price_`+fmt.Sprint(p.type)+` as price,
FROM products
WHERE products.id in (%s) and products.store= %s
在其他情况下(取决于请求),我可能会有这样的事情:
SELECT
price_`+fmt.Sprint(p.type)+` as price,
FROM products
WHERE products.id in ('testid1', 'testid2') and products.store= 2
UNION
SELECT
price_`+fmt.Sprint(p.type)+` as price,
FROM products
WHERE products.id in ('testid3', 'testid4') and products.store= 1
如果我确定查询是什么,我只会使用 $1、$2 等,但我不认为我可以在这里,因为我不知道会有多少参数并且它们都需要不同.
拉风的咖菲猫
相关分类