การเรียงลำดับผลลัพธ์ของคิวรี

Python เบื้องต้นสำหรับฐานข้อมูล

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Order by clause

  • ควบคุมลำดับการแสดงผลข้อมูลในผลลัพธ์ของคิวรี
  • ใช้งานผ่านเมธอด order_by() บน statement
Python เบื้องต้นสำหรับฐานข้อมูล

เรียงลำดับจากน้อยไปมาก

print(results[:10])
[('Illinois',), ...]
stmt = select([census.columns.state])

stmt = stmt.order_by(census.columns.state)
results = connection.execute(stmt).fetchall()
print(results[:10])
[('Alabama',), ...]
Python เบื้องต้นสำหรับฐานข้อมูล

เรียงลำดับจากมากไปน้อย

  • ครอบคอลัมน์ด้วย desc() ใน order_by() clause
Python เบื้องต้นสำหรับฐานข้อมูล

เรียงลำดับหลายคอลัมน์

  • คั่นหลายคอลัมน์ด้วยเครื่องหมายจุลภาค
  • เรียงตามคอลัมน์แรกก่อน
  • หากคอลัมน์แรกมีค่าซ้ำ จะเรียงตามคอลัมน์ถัดไป
  • ทำซ้ำจนครบทุกคอลัมน์
Python เบื้องต้นสำหรับฐานข้อมูล

เรียงลำดับหลายคอลัมน์

print(results)
('Alabama', 'M')
stmt = select([census.columns.state, census.columns.sex])

stmt = stmt.order_by(census.columns.state, census.columns.sex)
results = connection.execute(stmt).first() print(results)
('Alabama', 'F')
('Alabama', 'F')
...
('Alabama', 'M')
Python เบื้องต้นสำหรับฐานข้อมูล

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับฐานข้อมูล

Preparing Video For Download...