用戶可以根據許多不同的標準請求產品價格,這將導致它可能訪問表中的不同列。我正在遍歷請求的產品并構建一堆查詢,但遇到了一些麻煩。一個一個地運行它們并組合結果比將它們聯合起來需要更長的時間。因此,我嘗試構建如下查詢,它有效且速度快,但現在容易受到注入的影響。沒有聯盟有沒有更好的方法來做到這一點?或者有沒有一種簡單的方法可以參數化這樣的動態查詢? 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= 2UNIONSELECT price_`+fmt.Sprint(p.type)+` as price, FROM products WHERE products.id in ('testid3', 'testid4') and products.store= 1如果我確定查詢是什么,我只會使用 $1、$2 等,但我不認為我可以在這里,因為我不知道會有多少參數并且它們都需要不同.
1 回答

拉風的咖菲貓
TA貢獻1995條經驗 獲得超2個贊
弄清楚了,未經測試的粗略示例,說明我如何最終做到這一點,以防其他人遇到這種情況。
var counter int = 1
var parameters []interface{}
for _, d:= range data{
if counter != 1 {
fullQuery = fullQuery + " UNION "
}
fullQuery = fullQuery + fmt.Sprintf(`
SELECT
price_`+fmt.Sprint(d.type)+` as price,
FROM products
WHERE products.id = ANY($%v) and products.store= $%d
`, counter, counter+1)
counter+=2
parameters = append(parameters, pq.Array(d.ids), d.store)
}
err := sqlx.Select(db, &dataStruct, fullQuery, parameters...)
Will still need to validate column names prior to querying to prevent injection.
- 1 回答
- 0 關注
- 103 瀏覽
添加回答
舉報
0/150
提交
取消