Vztahy v SQL

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Vztahy

  • Umožňují předejít duplicitním datům
  • Usnadňují úpravy na jednom místě
  • Vhodné pro oddělení zřídka potřebných dat z tabulky
Introduction to Databases in Python

Vztahy

Introduction to Databases in Python

Automatická spojení

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

Join

  • Přijímá tabulku a volitelný výraz popisující vztah mezi tabulkami
  • Výraz není potřeba, pokud je vztah předdefinován a dostupný přes reflexi
  • Umísťuje se ihned za klauzuli select(), před where(), order_by() nebo group_by()
Introduction to Databases in Python

select_from()

  • Nahrazuje výchozí klauzuli FROM spojem
  • Obaluje klauzuli join()
Introduction to Databases in Python

Příklad select_from()

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

Spojení tabulek bez předdefinovaného vztahu

  • Join přijímá tabulku a volitelný výraz popisující vztah mezi tabulkami
  • Spojí pouze data, která si v obou sloupcích odpovídají
  • Vyhněte se spojování sloupců různých datových typů
Introduction to Databases in Python

Příklad select_from()

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

Pojďme si procvičit!

Introduction to Databases in Python

Preparing Video For Download...