SQLのリレーションシップ

Pythonで学ぶデータベース入門

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

リレーションシップ

  • 重複データを避けられる
  • 一箇所の変更で全体を更新しやすい
  • まれに使う情報をテーブルから切り出すのに有用
Pythonで学ぶデータベース入門

リレーションシップ

Pythonで学ぶデータベース入門

自動結合

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と、2つのテーブルの関連を示す任意の式を受け取る
  • リレーションが事前定義され反映で取得できる場合、式は不要
  • select() の直後、where()order_by()group_by() の前に置く
Pythonで学ぶデータベース入門

select_from()

  • 既定の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と、2つのテーブルの関連を示す任意の式を受け取る
  • 2つの列で一致するデータのみを結合
  • 型の異なる列での結合は避ける
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...