连接(Joins)
即使您不从两张表都选择列,或两张表之间没有定义好的关系,您仍然可以在一张表上使用 .join() 方法,将其与另一张表连接,从而获取与查询相关的更多数据。join() 的第一个参数是要连接进来的表对象,第二个参数是一个条件,用来指明两张表是如何关联的。最后,您需要在查询语句上使用 .select_from() 方法来包裹这个连接子句。例如,在视频中,Jason 执行了下面的代码,将 census 表与 state_fact 表连接,使得 census 表的 state 列对应到 state_fact 表的 name 列。
stmt = stmt.select_from(
census.join(
state_fact, census.columns.state ==
state_fact.columns.name)
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 构建一个语句,选择
census和state_fact两张表的所有列。比如,要选择两张表employees和sales的所有列,您可以使用stmt = select([employees, sales])。 - 在
stmt上追加select_from,按census表的state列与state_fact表的name列进行连接,将census表与state_fact表连接起来。 - 执行该语句以获取第一条结果,并将其保存为
result。这段代码已为您写好。 - 提交答案以遍历结果对象的键,并打印每个键及其对应的值!
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Build a statement to select the census and state_fact tables: stmt
stmt = select([____, ____])
# Add a select_from clause that wraps a join for the census and state_fact
# tables where the census state column and state_fact name column match
stmt_join = stmt.select_from(
____(____, census.columns.____ == state_fact.columns.____))
# Execute the statement and get the first result: result
result = connection.execute(stmt_join).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))