การ Join
แม้จะไม่ได้เลือกคอลัมน์จากทั้งสองตาราง หรือสองตารางนั้นยังไม่มีความสัมพันธ์ที่กำหนดไว้ล่วงหน้า ก็ยังสามารถใช้เมธอด .join() บนตารางเพื่อ join กับตารางอื่น และดึงข้อมูลเพิ่มเติมที่เกี่ยวข้องกับคิวรีได้ .join() รับออบเจ็กต์ตารางที่ต้องการ join เป็นอาร์กิวเมนต์แรก และเงื่อนไขที่ระบุความสัมพันธ์ระหว่างตารางเป็นอาร์กิวเมนต์ที่สอง จากนั้นใช้เมธอด .select_from() บน select statement เพื่อครอบ join clause ตัวอย่างเช่น ในวิดีโอ Jason รันโค้ดต่อไปนี้เพื่อ join ตาราง census กับตาราง state_fact โดยให้คอลัมน์ state ของตาราง census สอดคล้องกับคอลัมน์ name ของตาราง state_fact
stmt = stmt.select_from(
census.join(
state_fact, census.columns.state ==
state_fact.columns.name)
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
- สร้าง statement เพื่อเลือกคอลัมน์ทั้งหมดจากตาราง
censusและstate_factตัวอย่างเช่น หากต้องการเลือกคอลัมน์ทั้งหมดจากสองตารางemployeesและsalesให้ใช้stmt = select([employees, sales]) - เพิ่ม
select_fromต่อท้ายstmtเพื่อ join ตารางcensusกับตารางstate_factโดยใช้คอลัมน์stateจากตารางcensusและคอลัมน์nameจากตารางstate_fact - รัน statement เพื่อดึงผลลัพธ์แรกและบันทึกไว้ในตัวแปร
result(โค้ดส่วนนี้เขียนไว้ให้แล้ว) - กด ส่งคำตอบ เพื่อวนลูปผ่าน key ทั้งหมดของออบเจ็กต์
resultและแสดงผล key และ value แต่ละคู่
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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))