SQL-relaties

Introductie tot databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Relaties

  • Voorkomt dubbele data
  • Makkelijk aan te passen op één plek
  • Handig om zelden gebruikte info uit een tabel te halen
Introductie tot databases in Python

Relaties

Introductie tot databases in Python

Automatische joins

stmt = select([census.columns.pop2008, 
        state_fact.columns.abbreviation])

results = connection.execute(stmt).fetchall() print(results)
[(95012, u'IL'),
 (95012, u'NJ'),
 (95012, u'ND'),
 (95012, u'OR'),
 (95012, u'DC'),
 (95012, u'WI'),
 ...
Introductie tot databases in Python

Join

  • Accepteert een Table en optioneel een expressie die uitlegt hoe de tabellen samenhangen
  • De expressie is niet nodig als de relatie vooraf is gedefinieerd en via reflectie beschikbaar is
  • Komt direct na select() en vóór where(), order_by() of group_by()
Introductie tot databases in Python

select_from()

  • Vervangt de standaard, afgeleide FROM-clause door een join
  • Wrapt de join()-clause
Introductie tot databases in Python

select_from()-voorbeeld

stmt = select([func.sum(census.columns.pop2000)])

stmt = stmt.select_from(census.join(state_fact))
stmt = stmt.where(state_fact.columns.circuit_court == '10')
result = connection.execute(stmt).scalar() print(result)
14945252
Introductie tot databases in Python

Tabellen joinen zonder vooraf gedefinieerde relatie

  • Join accepteert een Table en optioneel een expressie die uitlegt hoe de tabellen samenhangen
  • Voegt alleen rijen samen waar de kolommen matchen
  • Vermijd joins op kolommen met verschillende types
Introductie tot databases in Python

select_from()-voorbeeld

stmt = select([func.sum(census.columns.pop2000)])

stmt = stmt.select_from( census.join(state_fact, census.columns.state == state_fact.columns.name))
stmt = stmt.where( state_fact.columns.census_division_name == 'East South Central')
result = connection.execute(stmt).scalar() print(result)
16982311
Introductie tot databases in Python

Laten we oefenen!

Introductie tot databases in Python

Preparing Video For Download...