การกรองข้อมูลจากตาราง - Expressions
นอกจาก Python comparators มาตรฐานแล้ว ยังสามารถใช้เมธอดอย่าง in_() เพื่อสร้าง where() clause ที่ทรงพลังยิ่งขึ้นได้อีกด้วย ดู expression ทั้งหมดได้ที่ SQLAlchemy Documentation
เมธอด in_() เมื่อใช้กับคอลัมน์ จะช่วยให้ดึงเฉพาะเรคคอร์ดที่ค่าของคอลัมน์นั้นตรงกับค่าใดค่าหนึ่งในลิสต์ที่กำหนด ตัวอย่างเช่น where(census.columns.age.in_([20, 30, 40])) จะคืนค่าเฉพาะเรคคอร์ดของคนที่มีอายุ 20, 30 หรือ 40 ปีเท่านั้น
ในแบบฝึกหัดนี้ จะทำงานกับตาราง census ต่อไป โดยเลือกเรคคอร์ดของผู้คนจาก 3 รัฐที่มีความหนาแน่นของประชากรสูงที่สุด ซึ่งได้เตรียมลิสต์ของรัฐเหล่านั้นไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
- เลือกทุกเรคคอร์ดจากตาราง
census - แก้ไข argument ของ
whereclause ให้ใช้in_()เพื่อดึงเรคคอร์ดทั้งหมดที่ค่าในคอลัมน์census.columns.stateอยู่ในลิสต์states - วนลูปผ่าน ResultProxy
connection.execute(stmt)และพิมพ์คอลัมน์stateและpop2000จากแต่ละเรคคอร์ด
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Define a list of states for which we want results
states = ['New York', 'California', 'Texas']
# Create a query for the census table: stmt
stmt = select(____)
# Append a where clause to match all the states in_ the list states
stmt = stmt.where(____)
# Loop over the ResultProxy and print the state and its population in 2000
for ____ in connection.execute(____):
print(____, ____)