การทำงานกับตารางแบบลำดับชั้น

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

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

ตารางแบบลำดับชั้น

  • มีความสัมพันธ์กับตัวเอง
  • พบได้บ่อยใน:
    • โครงสร้างองค์กร
    • ภูมิศาสตร์
    • เครือข่าย
    • กราฟ
Python เบื้องต้นสำหรับฐานข้อมูล

ตารางแบบลำดับชั้น - ตัวอย่าง

hierarchical_table.jpg

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

ตารางแบบลำดับชั้น - alias()

  • ต้องการวิธีอ้างถึงตารางด้วยชื่อหลายชื่อ
  • สร้างการอ้างอิงที่ไม่ซ้ำกันเพื่อนำไปใช้งาน
Python เบื้องต้นสำหรับฐานข้อมูล

การ Query ข้อมูลแบบลำดับชั้น

managers = employees.alias()

stmt = select( [managers.columns.name.label('manager'), employees.columns.name.label('employee')])
stmt = stmt.select_from(employees.join( managers, managers.columns.id == employees.columns.manager)
stmt = stmt.order_by(managers.columns.name)
print(connection.execute(stmt).fetchall())
[(u'FILLMORE', u'GRANT'),
 (u'FILLMORE', u'ADAMS'),
 (u'HARDING', u'TAFT'), ...
Python เบื้องต้นสำหรับฐานข้อมูล

group_by และ func

  • ต้องระบุ group_by() ให้ตรงกับ alias ที่ถูกต้อง
  • ระวังการใช้ฟังก์ชันกับคอลัมน์ที่เหมาะสม
  • หากไม่ได้ใช้ทั้ง alias และชื่อตารางในคิวรี ไม่ต้องสร้าง alias
Python เบื้องต้นสำหรับฐานข้อมูล

การ Query ข้อมูลแบบลำดับชั้น

managers = employees.alias()

stmt = select([managers.columns.name, func.sum(employees.columns.sal)])
stmt = stmt.select_from(employees.join( managers, managers.columns.id == employees.columns.manager)
stmt = stmt.group_by(managers.columns.name) print(connection.execute(stmt).fetchall())
[(u'FILLMORE', Decimal('96000.00')),
 (u'GARFIELD', Decimal('83500.00')),
 (u'HARDING', Decimal('52000.00')),
 (u'JACKSON', Decimal('197000.00'))]
Python เบื้องต้นสำหรับฐานข้อมูล

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

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

Preparing Video For Download...