SQL 關聯

Python 資料庫入門

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

關聯

  • 避免重複資料
  • 便於集中變更
  • 將不常用資訊拆到另一張表
Python 資料庫入門

關聯

Python 資料庫入門

自動連接(join)

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

Join

  • 接受一個 Table,以及可選的表達式來說明兩表如何關聯
  • 若關聯已預先定義且可透過反射取得,則可省略表達式
  • 緊接在 select() 之後,且位於 where()order_by()group_by() 之前
Python 資料庫入門

select_from()

  • 用來以 join 取代預設的衍生 FROM 子句
  • 需包在 join() 子句外
Python 資料庫入門

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

無預先關聯時的資料表連接

  • join 接受一個 Table,以及可選的表達式來說明兩表如何關聯
  • 只會在兩欄位值相符時連接
  • 避免在不同型別的欄位上連接
Python 資料庫入門

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

一起來練習吧!

Python 資料庫入門

Preparing Video For Download...