使用別名處理同表自連結查詢
在實務上,你常會遇到具有階層結構的資料表,例如員工與同時也是員工的主管。為了處理這類情況,你可能需要在不同欄位上將一個資料表與自己做連結。.alias() 方法可以建立資料表的副本,協助你完成這項工作。因為是同一張表,所以只需要在 where 子句中指定連結條件即可。
在本題中,你將使用 .alias() 方法建立查詢,將 employees 資料表與自身連結,找出每個人分別回報給誰。
本練習屬於課程
Python 資料庫入門
練習說明
- 將
employees資料表的別名儲存為managers。做法是對employees套用.alias()方法。 - 建立一個查詢,選出員工的
name與其主管的name。主管的name已為你選好。請使用label將employees的name欄位標記為'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)