ฝึกเพิ่มเติมกับการ JOIN
ใช้คำสั่ง select เดิมจากแบบฝึกหัดที่แล้วได้เลย แต่คราวนี้เพิ่มความท้าทายด้วยการดึงเฉพาะบางคอลัมน์ และนำตารางอีกตารางไปใช้ใน
คำสั่ง group_by()
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
- สร้างคำสั่งเพื่อ select:
- คอลัมน์
stateจากตารางcensus - ผลรวมของคอลัมน์
pop2008จากตารางcensus - คอลัมน์
census_division_nameจากตารางstate_fact
- คอลัมน์
- ต่อท้าย
.select_from()เข้ากับstmtเพื่อ JOIN ตารางcensusและstate_factโดยใช้คอลัมน์stateและname - จัดกลุ่มคำสั่งด้วยคอลัมน์
nameของตารางstate_fact - รันคำสั่ง
stmt_groupedเพื่อดึงข้อมูลทั้งหมดและบันทึกไว้ในตัวแปรresults - กด ส่งคำตอบ เพื่อวนลูปผ่านออบเจ็กต์
resultsและพิมพ์แต่ละรายการ
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Build a statement to select the state, sum of 2008 population and census
# division name: stmt
stmt = select([
____,
func.sum(____),
____
])
# Append select_from to join the census and state_fact tables by the census state and state_fact name columns
stmt_joined = stmt.select_from(
census.join(____, census.columns.____ == state_fact.columns.____)
)
# Append a group by for the state_fact name column
stmt_grouped = stmt_joined.group_by(____)
# Execute the statement and get the results: results
results = connection.execute(____).fetchall()
# Loop over the results object and print each record.
for record in results:
print(record)