Práce s hierarchickými tabulkami

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Hierarchické tabulky

  • Obsahují vztah samy se sebou
  • Běžně se vyskytují v:
    • Organizačních
    • Geografických
    • Síťových
    • Grafových
Introduction to Databases in Python

Hierarchické tabulky – příklad

Příklad hierarchické tabulky

Introduction to Databases in Python

Hierarchické tabulky – alias()

  • Vyžaduje možnost zobrazit tabulku pod více názvy
  • Vytváří jedinečný odkaz, který lze využít
Introduction to Databases in Python

Dotazování hierarchických dat

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'), ...
Introduction to Databases in Python

group_by a func

  • Je důležité použít group_by() na správný alias
  • Dávejte pozor, na co funkce aplikujete
  • Pokud v dotazu nepoužijete alias i název tabulky zároveň, alias nevytvářejte
Introduction to Databases in Python

Dotazování hierarchických dat

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'))]
Introduction to Databases in Python

Pojďme si procvičit!

Introduction to Databases in Python

Preparing Video For Download...