0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLで複合キーの複数データ取得するための条件を作成【Python】

Posted at

説明

ループで条件を作成

  • enumerate() を使って、data の各要素をループしています。
  • start=1 でカウンタを1から始めます。

各ループのステップで以下の処理を行っています

  • (id = :id{cnt} AND code = :code{cnt}) という文字列を cond リストに追加。
  • param 辞書にパラメータとして idcode の値をキー付きで追加 (id{cnt}code{cnt} 形式)。

例えば、最初のループでは次のように処理されます

  • cond.append('(id = :id1 AND code = :code1)')
  • param['id1'] = 10
  • param['code1'] = 'A10'

条件の結合

  • cond リストに保存された各条件を " OR " で結合し、最終的なSQL条件を作成します。
data = [
    { 'id': 10, 'code': 'A10' },
    { 'id': 20, 'code': 'A20' },
    { 'id': 30, 'code': 'A30' },
]

cond = []
param = {}
for cnt, item in enumerate(data, start=1):
    cond.append(f'(id = :id{cnt} AND code = :code{cnt})')
    param[f'id{cnt}'] = item['id']
    param[f'code{cnt}'] = item['code']

print(" OR ".join(cond))
# (id = :id1 AND code = :code1) OR (id = :id2 AND code = :code2) OR (id = :id3 AND code = :code3)

print(param)
# {'id1': 10, 'code1': 'A10', 'id2': 20, 'code2': 'A20', 'id3': 30, 'code3': 'A30'}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?