開始使用免費開始

使用既有關聯自動進行連接

如果兩個資料表之間已經建立了關聯,你只要在 select 陳述式中加入想要的欄位,就能自動利用這個關聯。回想 Jason 建立了以下查詢:

stmt = select([census.columns.pop2008, state_fact.columns.abbreviation])

用來連接 censusstate_fact 兩個資料表,並從前者選取 pop2008 欄位、從後者選取 abbreviation 欄位。在這個例子中,censusstate_fact 之間有預先定義的關聯:前者的 state 欄位對應到後者的 name 欄位。

在本練習中,你會用相同的預先定義關聯,來選取 pop2000abbreviation 兩個欄位!

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • 建立一個陳述式,連接 censusstate_fact 資料表,並從前者選取 pop2000 欄位、從後者選取 abbreviation 欄位。
  • 執行該陳述式,取得第一筆結果並將其儲存為 result
  • 送出答案以迴圈走訪結果物件的所有鍵,並列印每個鍵與其值!

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Build a statement to join census and state_fact tables: stmt
stmt = select([____, ____])

# Execute the statement and get the first result: result
result = connection.execute(____).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))
編輯並執行程式碼