開始使用免費開始

Joins

即使你沒有同時選取兩個資料表的欄位,或兩個資料表之間沒有預先定義的關聯,你仍然可以在資料表上使用 .join() 方法,把它與另一個資料表連接,取得查詢相關的額外資料。join() 的第一個引數是你想要連接進來的資料表物件,第二個引數則是用來說明兩個資料表如何關聯的條件。最後,在查詢物件上使用 .select_from() 方法,把 join 子句包起來。例如,在影片中,Jason 執行了以下程式碼,將 census 資料表連接到 state_fact 資料表,使 census 資料表的 state 欄位對應到 state_fact 資料表的 name 欄位。

stmt = stmt.select_from(
    census.join(
        state_fact, census.columns.state == 
        state_fact.columns.name)

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • 建立一個查詢陳述,從 censusstate_fact 兩個資料表選取所有欄位。舉例來說,若要從 employeessales 兩個資料表選取所有欄位,你會使用 stmt = select([employees, sales])
  • stmt 上附加 select_from,依據 censusstate 欄位與 state_factname 欄位,將 censusstate_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))
編輯並執行程式碼