2017-10-12 50 views
0

我一直在嘗試在golang中使用postgres IN子句,但不斷收到錯誤。這是我想要執行的查詢。在golang中使用postgres IN子句

SELECT id1 FROM my_table WHERE type = (an int) AND id2 = (an int) AND id1 IN (list of UUIDs) 

我用這段代碼來構造這個查詢,但得到了下面的錯誤。

var params []interface{} 
inCondition := "" 
params = append(params, type) 
params = append(params, id2) 
for _, id := range id1 { 
    params = append(params, id) 
    if inCondition != "" { 
     inCondition += ", " 
    } 
    inCondition += "?" 
} 
query := fmt.Sprintf(`SELECT id1 FROM my_table WHERE type = ? AND id2 = ? AND id1 IN (%s)`, inCondition) 
rows, err := db.Query(query, params...) 

查詢我:

SELECT id1 FROM my_table WHERE type = ? AND id2 = ? AND id1 IN (?, ?, ?) 

PARAMS輸出:

[]interface {}=[0 7545449 d323f8d5-ab97-46a3-a34e-95ceac2f3a6a d323f8d5-ab97-46a3-a34e-95ceac2f3a6b d323f8d5-ab97-46a3-a34e-95ceac2f3a6d] 

錯誤:

pq: syntax error at or near \"AND\"" 

我缺少什麼?或者,我將如何獲得這個工作? id1是一段長度可變的UUID。

+0

*從不*使用字符串插值構建查詢。至少不是沒有仔細引用一切。這是大規模的SQL注入誘餌。改爲使用綁定參數。例如https://godoc.org/github.com/lib/pq#Array –

+2

你使用['lib/pq'](https://github.com/lib/pq)?對於參數的佔位符,而不是'?',請嘗試'$ 1,$ 2 ...'。 – putu

+0

你能顯示整個結果查詢嗎?可能在數據庫錯誤日誌上。嘗試對IN查詢使用特殊插值。 –

回答

0

而不是?,使用$ 1,$ 2等作爲佔位符工作。

+0

雅,Postgres不接受'?'佔位符。但是,如果您使用[sqlx](https://github.com/jmoiron/sqlx),它允許您使用任何語言的'?'(以及命名參數,如':entry_id'),然後重新映射它們通過'Rebind()'來回答相關語言。還有一些其他功能可以使SQL查詢的煩人度降低很多(例如直接掃描結構的能力)。 – Kaedys