การกรองและเลือกข้อมูล

Python เบื้องต้นสำหรับฐานข้อมูล

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Where clause

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
...
Python เบื้องต้นสำหรับฐานข้อมูล

Where clause

  • กรองข้อมูลที่คิวรีส่งคืนโดยใช้เงื่อนไข Boolean
  • เปรียบเทียบคอลัมน์กับค่าหนึ่งหรือคอลัมน์อื่น
  • มักใช้ตัวดำเนินการ ==, <=, >=, หรือ !=
Python เบื้องต้นสำหรับฐานข้อมูล

Expression

  • กำหนดเงื่อนไขที่ซับซ้อนกว่าตัวดำเนินการพื้นฐาน
  • เช่น in_(), like(), between()
  • มีเพิ่มเติมในเอกสารอ้างอิง
  • ใช้งานเป็น method บน Column
Python เบื้องต้นสำหรับฐานข้อมูล

Expression

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
...
Python เบื้องต้นสำหรับฐานข้อมูล

Conjunction

  • ช่วยกำหนดเงื่อนไขหลายข้อใน where clause
  • เช่น and_(), or_(), not_()
Python เบื้องต้นสำหรับฐานข้อมูล

Conjunction

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
Python เบื้องต้นสำหรับฐานข้อมูล

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับฐานข้อมูล

Preparing Video For Download...