結合(Joins)
両方のテーブルから列を選択しない場合や、2 つのテーブルのリレーションシップが定義されていない場合でも、あるテーブルに対して .join() メソッドを使って別のテーブルと結合し、クエリに関連する追加データを取得できます。join() は、最初の引数に結合対象のテーブルオブジェクト、2 番目の引数にテーブル同士がどのように関連しているかを示す条件を取ります。最後に、select 文に対して .select_from() メソッドを使い、join 句を指定します。たとえば動画では、Jason は次のコードを実行して、census テーブルの state 列が state_fact テーブルの name 列に対応するように、census テーブルと state_fact テーブルを結合しました。
stmt = stmt.select_from(
census.join(
state_fact, census.columns.state ==
state_fact.columns.name)
この演習はコースの一部です
Pythonで学ぶデータベース入門
演習の手順
censusとstate_factの両テーブルから ALL の列を選択するステートメントを作成します。たとえば、2 つのテーブルemployeesとsalesから ALL の列を選ぶには、stmt = select([employees, sales])を使います。stmtにselect_fromを追加し、censusテーブルのstate列とstate_factテーブルのname列でcensusテーブルをstate_factテーブルに結合します。- ステートメントを実行して最初の結果を取得し、
resultに保存します。このコードはすでに用意されています。 - 結果オブジェクトのキーをループして、それぞれのキーと値を出力し、回答を提出してください!
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Build a statement to select the census and state_fact tables: stmt
stmt = select([____, ____])
# Add a select_from clause that wraps a join for the census and state_fact
# tables where the census state column and state_fact name column match
stmt_join = stmt.select_from(
____(____, census.columns.____ == state_fact.columns.____))
# Execute the statement and get the first result: result
result = connection.execute(stmt_join).first()
# Loop over the keys in the result object and print the key and value
for key in result.keys():
print(key, getattr(result, key))