2
0

More than 3 years have passed since last update.

spannerでwhere inで検索する

Posted at

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のドキュメントをもっと読んでいかないと。。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0