處理階層式資料表

Python 資料庫入門

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

階層式資料表

  • 自我關聯
  • 常見於:
    • 組織
    • 地理
    • 網路
    • 圖形
Python 資料庫入門

階層式資料表:範例

階層式資料表

Python 資料庫入門

階層式資料表:alias()

  • 需要以多個別名檢視同一資料表
  • 建立可重複使用的唯一參照
Python 資料庫入門

查詢階層式資料

managers = employees.alias()

stmt = select( [managers.columns.name.label('manager'), employees.columns.name.label('employee')])
stmt = stmt.select_from(employees.join( managers, managers.columns.id == employees.columns.manager)
stmt = stmt.order_by(managers.columns.name)
print(connection.execute(stmt).fetchall())
[(u'FILLMORE', u'GRANT'),
 (u'FILLMORE', u'ADAMS'),
 (u'HARDING', u'TAFT'), ...
Python 資料庫入門

group_by 與 func

  • group_by() 用在正確的別名上很重要
  • 小心你套用函式的對象
  • 若查詢中不會同時用到別名與原表名,就不要建立別名
Python 資料庫入門

查詢階層式資料

managers = employees.alias()

stmt = select([managers.columns.name, func.sum(employees.columns.sal)])
stmt = stmt.select_from(employees.join( managers, managers.columns.id == employees.columns.manager)
stmt = stmt.group_by(managers.columns.name) print(connection.execute(stmt).fetchall())
[(u'FILLMORE', Decimal('96000.00')),
 (u'GARFIELD', Decimal('83500.00')),
 (u'HARDING', Decimal('52000.00')),
 (u'JACKSON', Decimal('197000.00'))]
Python 資料庫入門

一起來練習吧!

Python 資料庫入門

Preparing Video For Download...