Làm việc với bảng phân cấp

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

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Bảng phân cấp

  • Có quan hệ với chính nó
  • Thường thấy trong:
    • Tổ chức
    • Địa lý
    • Mạng
    • Đồ thị
Nhập môn Cơ sở dữ liệu với Python

Ví dụ về bảng phân cấp

bảng_phân_cấp.jpg

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

Bảng phân cấp - alias()

  • Cần cách xem bảng qua nhiều tên
  • Tạo tham chiếu duy nhất để dùng
Nhập môn Cơ sở dữ liệu với Python

Truy vấn dữ liệu phân cấp

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

group_by và func

  • Cần nhắm group_by() vào đúng bí danh
  • Cẩn thận với cột dùng để áp dụng hàm
  • Nếu không cần cả bí danh và tên bảng cho truy vấn, đừng tạo bí danh
Nhập môn Cơ sở dữ liệu với Python

Truy vấn dữ liệu phân cấp

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'))]
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...