篩選與鎖定資料

Python 資料庫入門

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

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
...
Python 資料庫入門

Where 子句

  • 依布林條件限制查詢回傳的資料
  • 比較欄位與某值或另一欄位
  • 常用比較:==<=>=!=
Python 資料庫入門

運算式(Expressions)

  • 提供比單純運算子更複雜的條件
  • 例如 in_()like()between()
  • 更多可見於文件
  • 作為 Column 的方法提供
Python 資料庫入門

運算式(Expressions)

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 資料庫入門

連接詞(Conjunctions)

  • 讓 where 子句包含多個條件
  • 例如 and_()or_()not_()
Python 資料庫入門

連接詞(Conjunctions)

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...