Řazení výsledků dotazu

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Klauzule ORDER BY

  • Umožňuje řídit pořadí vrácených záznamů ve výsledcích dotazu
  • Dostupná jako metoda na výrazech order_by()
Introduction to Databases in Python

Řazení vzestupně

print(results[:10])
[('Illinois',), ...]
stmt = select([census.columns.state])

stmt = stmt.order_by(census.columns.state)
results = connection.execute(stmt).fetchall()
print(results[:10])
[('Alabama',), ...]
Introduction to Databases in Python

Řazení sestupně

  • Sloupeček zabalte do desc() v klauzuli order_by()
Introduction to Databases in Python

Řazení podle více sloupců

  • Více sloupců oddělte čárkou
  • Výsledky se nejprve seřadí podle prvního sloupce
  • Duplicity v prvním sloupci se řadí podle druhého sloupce
  • Postup se opakuje pro všechny sloupce
Introduction to Databases in Python

Řazení podle více sloupců

print(results)
('Alabama', 'M')
stmt = select([census.columns.state, census.columns.sex])

stmt = stmt.order_by(census.columns.state, census.columns.sex)
results = connection.execute(stmt).first() print(results)
('Alabama', 'F')
('Alabama', 'F')
...
('Alabama', 'M')
Introduction to Databases in Python

Pojďme procvičovat!

Introduction to Databases in Python

Preparing Video For Download...