Sắp xếp kết quả truy vấn

Nhập môn Cơ sở dữ liệu với Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Mệnh đề Order by

  • Cho phép kiểm soát thứ tự bản ghi trong kết quả truy vấn
  • Dùng như phương thức order_by() trên câu lệnh
Nhập môn Cơ sở dữ liệu với Python

Sắp xếp tăng dần

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',), ...]
Nhập môn Cơ sở dữ liệu với Python

Sắp xếp giảm dần

  • Bọc cột bằng desc() trong order_by()
Nhập môn Cơ sở dữ liệu với Python

Sắp xếp theo nhiều cột

  • Chỉ cần ngăn cách nhiều cột bằng dấu phẩy
  • Sắp xếp hoàn toàn theo cột thứ nhất
  • Nếu cột thứ nhất trùng, sắp xếp theo cột thứ hai
  • Lặp lại cho đến khi tất cả cột được sắp xếp
Nhập môn Cơ sở dữ liệu với Python

Sắp xếp theo nhiều cột

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')
Nhập môn Cơ sở dữ liệu với Python

Ayo berlatih!

Nhập môn Cơ sở dữ liệu với Python

Preparing Video For Download...