開始使用免費開始

使用別名處理同表自連結查詢

在實務上,你常會遇到具有階層結構的資料表,例如員工與同時也是員工的主管。為了處理這類情況,你可能需要在不同欄位上將一個資料表與自己做連結。.alias() 方法可以建立資料表的副本,協助你完成這項工作。因為是同一張表,所以只需要在 where 子句中指定連結條件即可。

在本題中,你將使用 .alias() 方法建立查詢,將 employees 資料表與自身連結,找出每個人分別回報給誰。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • employees 資料表的別名儲存為 managers。做法是對 employees 套用 .alias() 方法。
  • 建立一個查詢,選出員工的 name 與其主管的 name。主管的 name 已為你選好。請使用 labelemployeesname 欄位標記為 'employee'
  • stmt 中加入 where 子句,使 managers 資料表的 id 欄位對應到 employees 資料表的 mgr 欄位。
  • managers 資料表的 name 欄位排序。
  • 執行查詢並儲存所有結果。這段程式碼已經提供。送出答案後會印出所有主管與其員工的姓名。

動手互動練習

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

# Make an alias of the employees table: managers
managers = ____

# Build a query to select names of managers and their employees: stmt
stmt = select(
    [managers.columns.name.label('manager'),
     ____]
)

# Match managers id with employees mgr: stmt_matched
stmt_matched = stmt.where(managers.columns.id == ____)

# Order the statement by the managers name: stmt_ordered
stmt_ordered = stmt_matched.order_by(____)

# Execute statement: results
results = connection.execute(stmt_ordered).fetchall()

# Print records
for record in results:
    print(record)

編輯並執行程式碼