spannerで複数条件で検索するときにwhere inを使って書く方法を調べたのでまとめます。
修正前
names := []string{"Alice", "Bob"}
stmt := spanner.Statement{
SQL: "SELECT * FROM Users WHERE Name IN (@Names)",
Params: map[string]interface{}{
"Names": strings.Join(names, ","),
},
}
このコードだと、namesが一つの場合には、問題なく動きます。
複数の場合には、Alice,Bob
で一つの文字列として扱われるため、検索に失敗します。
修正後
names := []string{"Alice", "Bob"}
stmt := spanner.Statement{
SQL: "SELECT * FROM Users WHERE Name IN UNNEST(@Names)",
Params: map[string]interface{}{
"Names": names,
},
}
公式にサンプルがあったのでそのままですが、上記のようになりました。
UNNEST
が配列を使う点がポイントです。
UNNEST 演算子は ARRAY を受け取り、ARRAY 内の各要素を 1 行にしてテーブルを返します。
IN句の詳細はこちらにあるので参照してください。
https://cloud.google.com/spanner/docs/operators?hl=ja#in_operators
まとめ
spannerのドキュメントをもっと読んでいかないと。。