始める無料で始める

テーブルから選択したデータをフィルタする - 基本

データベースに接続できたので、次はクエリのフィルタリングを練習しましょう。

動画でも説明したとおり、where() 句はステートメントが返すデータを絞り込むために使います。たとえば、census テーブルから性別が女性('F')のレコードをすべて選択するには、次のように書きます。

select([census]).where(census.columns.sex == 'F')

== に加えて、where() 句の中では基本的にあらゆる Python の比較演算子(<= や != など)を使えます。

この演習はコースの一部です

Pythonで学ぶデータベース入門

コースを見る

演習の手順

  • select() に census をリストとして渡し、census テーブルのすべてのレコードを選択します。
  • stmt に where 句を追加し、state が 'New York' のレコードだけを返すようにします。
  • connection の .execute() でステートメント stmt を実行し、.fetchall() で結果を取得します。
  • results を反復処理し、各レコードから age、sex、pop2000 列を出力します。たとえば、result.age で result の age を出力できます。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Create a select query: stmt
stmt = ____

# Add a where clause to filter the results to only those for New York : stmt_filtered
stmt = stmt.____

# Execute the query to retrieve all the data returned: results
results = ____

# Loop over the results and print the age, sex, and pop2000
for ___ in ____:
    print(result.age, ____, ____)
コードを編集して実行