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

  • 接受一个表和一个可选表达式,说明两表如何关联
  • 若关系已预定义并可通过反射获得,则无需该表达式
  • 紧跟在 select() 之后,先于 where()order_by()group_by()
Python 中的数据库入门

select_from()

  • 用于将默认的派生 FROM 子句替换为 join
  • 包装 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 接受一个表和一个可选表达式,用于说明两表如何关联
  • 只在两列值匹配时进行连接
  • 避免在不同数据类型的列上连接
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...