示例表架構:
create table t1(
col1 varchar(20),
col2 varchar(20)
);
要求:獲取與陣列中出現的任何元組 (col1, col2) 匹配的行。
查詢陳述句:
select * from t1 where (col1, col2) in (('c11', 'c12'), ('c21', 'c22'));
我想使用帶有“github.com/lib/pq”驅動程式的“database/sql”包在 Go 中撰寫這個查詢,這就是我面臨的問題。
對于單列 IN/ANY 查詢,我可以輕松做到這一點。
例如,以下查詢
select * from t1 where col1 in ('c11', 'c21');
可以使用以下代碼片段來實作:
args := []string{"c11", "c21}
conn.Exec(`select * from t1 where col1 = any($1)`, pq.Array(args))
但是,我無法對多列查詢使用類似的方法。我嘗試將等作為引數傳遞pq.Array([][]string),pq.Array([]*pq.StringArray)但它們不起作用,并獲取以下錯誤:
input of anonymous composite types is not implemented
將不勝感激這方面的任何幫助。
uj5u.com熱心網友回復:
您可以執行以下操作:
args := [][]string{{"c11","c21"},{"c21","c22"}}
params := make([]interface{}, len(args)*2)
tuples := make([]string, len(args))
for i := range args {
params[i*2] = args[i][0]
params[i*2 1] = args[i][1]
tuples[i] = fmt.Sprintf("($%d,$%d)", i*2 1,i*2 2)
}
invals := "(" strings.Join(tuples, ",")) ")"
conn.Exec("SELECT * FROM t1 WHERE (col1,col2) IN " invals, params...)
對于兩列元組,您應該能夠執行以下操作:
conn.Exec(`SELECT * FROM t1 WHERE (col1,col2) IN (
SELECT * FROM json_each_text(json_object($1::text[]))
)`, pq.Array([][]string{{"c11","c21"},{"c21","c22"}}))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371083.html
標籤:sql 数据库 PostgreSQL的 走
上一篇:natsClient.Subscribe("some_subject",some_callback):'some_callback'回呼是否在Golang自己的
