การกรองข้อมูลจากตาราง - ขั้นสูง
เริ่มเข้าใจได้ดีแล้ว! SQLAlchemy ยังรองรับการใช้ conjunction เช่น and_(), or_() และ
not_() เพื่อสร้างเงื่อนไขการกรองที่ซับซ้อนยิ่งขึ้น ตัวอย่างเช่น เราสามารถดึงข้อมูลของผู้ที่อยู่ในนิวยอร์กและมีอายุ 21 หรือ 37 ปีได้ด้วยโค้ดต่อไปนี้:
select([census]).where(
and_(census.columns.state == 'New York',
or_(census.columns.age == 21,
census.columns.age == 37
)
)
)
คำสั่ง SQL ที่เทียบเท่าจะมีลักษณะดังนี้
SELECT * FROM census WHERE state = 'New York' AND (age = 21 OR age = 37)
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
- นำเข้า
and_จากโมดูลsqlalchemy - เลือกข้อมูลทุกแถวจากตาราง
census - เพิ่ม where clause เพื่อกรองเฉพาะแถวที่
stateเป็น'California'และsexไม่ใช่'M' - รัน
stmtผ่าน connection แล้ววนลูปผ่าน ResultProxy เพื่อพิมพ์คอลัมน์ageและsexจากแต่ละแถว
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import and_
from ____ import ____
# Build a query for the census table: stmt
stmt = select(____)
# Append a where clause to select only non-male records from California using and_
stmt = stmt.where(
# The state of California with a non-male sex
____(census.columns.state == ____,
census.columns.sex != ____
)
)
# Loop over the ResultProxy printing the age and sex
for result in ____:
print(____, ____)