开始使用免费开始使用

基于既有关系的自动连接

如果两张表之间已经建立了关系,您只需把各自需要的列添加到 select 语句中,就可以自动利用该关系。回忆一下,Jason 构造了如下查询:

stmt = select([census.columns.pop2008, state_fact.columns.abbreviation])

用于连接 censusstate_fact 两张表,并从前者选择 pop2008 列、从后者选择 abbreviation 列。在这个例子中,censusstate_fact 表有一个预定义关系:前者的 state 列对应后者的 name 列。

在本练习中,您将使用同样的预定义关系来选择 pop2000abbreviation 两列!

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • 构建一条语句,连接 censusstate_fact 表,并从前者选择 pop2000 列、从后者选择 abbreviation 列。
  • 执行该语句,获取第一条结果并保存为 result
  • 提交答案以遍历结果对象的键,并打印每个键及其对应的值!

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Build a statement to join census and state_fact tables: stmt
stmt = select([____, ____])

# Execute the statement and get the first result: result
result = connection.execute(____).first()

# Loop over the keys in the result object and print the key and value
for key in result.keys():
    print(key, getattr(result, key))
编辑并运行代码