テーブルから選択したデータをフィルタする - 式
標準的な Python の比較演算子に加えて、in_() のようなメソッドを使って、より強力な where() 句を作成できます。利用可能な式の一覧は、SQLAlchemy Documentationで確認できます。
in_() メソッドは列に対して使うと、その列の値が指定した候補リストのいずれかに含まれるレコードだけを取り込めます。例えば、where(census.columns.age.in_([20, 30, 40])) は、年齢がちょうど 20、30、または 40 歳の人のレコードだけを返します。
この演習では、引き続き census テーブルを使い、人口密度が最も高い 3 州の人々のレコードを選択します。これらの州のリストはすでに用意されています。
この演習はコースの一部です
Pythonで学ぶデータベース入門
演習の手順
censusテーブルからすべてのレコードを選択します。where句の引数を修正し、in_()を使って、census.columns.state列の値がstatesリストに含まれるすべてのレコードを返すようにします。- ResultProxy
connection.execute(stmt)をループし、各レコードのstate列とpop2000列を出力します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Define a list of states for which we want results
states = ['New York', 'California', 'Texas']
# Create a query for the census table: stmt
stmt = select(____)
# Append a where clause to match all the states in_ the list states
stmt = stmt.where(____)
# Loop over the ResultProxy and print the state and its population in 2000
for ____ in connection.execute(____):
print(____, ____)