Lọc và nhắm mục tiêu dữ liệu

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

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Mệnh đề WHERE

stmt = select([census])

stmt = stmt.where(census.columns.state == 'California')
results = connection.execute(stmt).fetchall()
for result in results: print(result.state, result.age)
California 0
California 1
California 2
California 3
California 4
California 5
...
Nhập môn Cơ sở dữ liệu với Python

Mệnh đề WHERE

  • Hạn chế dữ liệu trả về dựa trên điều kiện Boolean
  • So sánh một cột với một giá trị hoặc cột khác
  • Thường dùng toán tử ==, <=, >=, hoặc !=
Nhập môn Cơ sở dữ liệu với Python

Biểu thức

  • Cung cấp điều kiện phức tạp hơn so với toán tử đơn giản
  • Ví dụ: in_(), like(), between()
  • Xem thêm trong tài liệu
  • Có sẵn dưới dạng phương thức của Column
Nhập môn Cơ sở dữ liệu với Python

Biểu thức

stmt = select([census])

stmt = stmt.where(census.columns.state.startswith('New'))
for result in connection.execute(stmt): print(result.state, result.pop2000)
New Jersey 56983
New Jersey 56686
New Jersey 57011
...
Nhập môn Cơ sở dữ liệu với Python

Liên kết logic

  • Cho phép nhiều tiêu chí trong một mệnh đề WHERE
  • Ví dụ: and_(), or_(), not_()
Nhập môn Cơ sở dữ liệu với Python

Liên kết logic

from sqlalchemy import or_

stmt = select([census])
stmt = stmt.where( or_(census.columns.state == 'California', census.columns.state == 'New York' ) )
for result in connection.execute(stmt): print(result.state, result.sex)
New York M
...
California F
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...