使用层级表

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 中的数据库入门

¡Vamos a practicar!

Python 中的数据库入门

Preparing Video For Download...