Quan hệ SQL

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

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Quan hệ

  • Tránh trùng lặp dữ liệu
  • Dễ thay đổi tại một nơi
  • Hữu ích để tách thông tin ít dùng khỏi bảng chính
Nhập môn Cơ sở dữ liệu với Python

Quan hệ

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

Nối tự động

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

Join

  • Nhận một Table và một biểu thức tùy chọn mô tả quan hệ giữa hai bảng
  • Không cần biểu thức nếu quan hệ đã được định nghĩa và phản chiếu sẵn
  • Đặt ngay sau select() và trước where(), order_by() hoặc group_by()
Nhập môn Cơ sở dữ liệu với Python

select_from()

  • Dùng để thay thế mệnh đề FROM mặc định bằng một join
  • Bao bọc mệnh đề join()
Nhập môn Cơ sở dữ liệu với Python

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

Nối bảng khi chưa có quan hệ định nghĩa sẵn

  • Join nhận một Table và một biểu thức tùy chọn mô tả quan hệ giữa hai bảng
  • Chỉ nối các hàng có giá trị khớp giữa hai cột
  • Tránh nối trên các cột khác kiểu dữ liệu
Nhập môn Cơ sở dữ liệu với Python

Ví dụ 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
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...