Closure Table สำหรับการคำนวณความสัมพันธ์
Relationship query ในครอบครัว — 'คนสองคนนี้เกี่ยวข้องกันไหม', 'degree of separation คืออะไร', 'ใครบ้างที่อยู่ใน subtree นี้' — ทำให้ naive database schema ล้มเหลวอย่างน่าเจ็บใจ Recursive CTE ทำงานแต่ช้าสำหรับ tree ขนาดใหญ่ Adjacency list ง่ายต่อการ write แต่ยากต่อการ query Closure table pattern แก้ปัญหาสิ่งเหล่านี้ด้วยต้นทุนที่ยอมรับได้
Closure Table คืออะไร
Closure table เก็บ row สำหรับทุก ancestor-descendant pair ในต้นไม้ ถ้า A เป็น parent ของ B และ B เป็น parent ของ C table จะมี row: (A, A, 0), (A, B, 1), (A, C, 2), (B, B, 0), (B, C, 1), (C, C, 0)
CREATE TABLE family_closure (
ancestor_id UUID NOT NULL REFERENCES persons(id),
descendant_id UUID NOT NULL REFERENCES persons(id),
depth INTEGER NOT NULL,
PRIMARY KEY (ancestor_id, descendant_id)
);
Query ที่ง่ายขึ้น
หา descendants ทั้งหมดของบุคคล: SELECT descendant_id FROM family_closure WHERE ancestor_id = $1 AND depth > 0
ตรวจสอบว่าสองคนเกี่ยวข้องกันผ่าน lineage ร่วม: หา common ancestor จากนั้นคำนวณ path