用戶可以根據許多不同的標準請求產品價格,這將導致它可能訪問表中的不同列。我正在遍歷請求的產品并構建一堆查詢,但遇到了一些麻煩。
一個一個地運行它們并組合結果比聯合它們需要更長的時間。因此,我嘗試構建如下查詢,該查詢有效且速度快,但現在容易受到注入。
在沒有聯盟的情況下,有沒有更好的方法來做到這一點?或者有沒有一種簡單的方法可以引數化這樣的動態查詢?
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 等,但我不認為我可以在這里,因為我不知道會有多少引數,而且它們都需要不同.
uj5u.com熱心網友回復:
想出來了,粗略的未經測驗的例子,說明我如何最終做到這一點,以防其他人遇到這種情況。
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...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/401956.html
標籤:PostgreSQL的 去 准备好的语句 psql
