سؤال

لديّ قاعدة بيانات هرمية ، على سبيل المثال ، أعمدة ID و PARENT_ID محددة لكل صف ، مع وجود صفوف المستوى الأعلى NULL PARENT_ID.

لديّ جميع العلاقات من هذا الجدول مسطحة في جدول آخر ، على سبيل المثال ، إذا كان هناك ثلاثة سجلات في التسلسل الهرمي الواحد من الجد ، والوالد ، الحفيد ، سيكون هناك 3 سجلات:

**ANCESTOR, DESCENDANT**
grantparent, parent
grandparent, grandchild
parent, grandchild

بدلاً من تنفيذ استعلام هرمي لتحديد أن الحفيد هو سليل من الجد يمكنني ببساطة التحقق من وجود أ (grandparent, grandchild) سجل في هذا الجدول المسطح.

سؤالي هو ، باستخدام هذا الجدول المسطح ، كيف يمكنني إرجاع جميع السجلات بشكل أكثر كفاءة بين العقدتين. باستخدام المثال ، مع grandparent و grandchild كمعلمات بلدي ، كيف يمكنني استعادة (grandparent, parent) سجل.

لا أريد استخدام استعلام هرمي لحل هذا ... أتساءل عما إذا كان من الممكن القيام بذلك دون أي نصلات.

هل كانت مفيدة؟

المحلول

SELECT  *
FROM    mytable
WHERE   descendant = @descendant
        AND hops < 
        (
        SELECT  hops
        FROM    mytable
        WHERE   descendant = @descendant
                AND ancestor = @ancestor
        )

سيؤدي هذا تلقائيًا إلى رعاية الحالات عندما @ancestor ليس حقا أ @descendantسلف.

إنشاء فهرس على (descendant, hops) لهذا العمل بسرعة.

نصائح أخرى

محاولة:

select h1.descendant intermediate_node
from hierarchy h0 
join hierarchy h1 
  on h0.ancestor = h1.ancestor 
 and h0.hops > h1.hops  -- redundant condition, but may improve performance
join hierarchy h2
  on h1.ancestor = h2.ancestor 
 and h0.descendant = h2.descendant
where h0.ancestor = :ancestor and h0.descendant = :descendant
SELECT
   distinct ancestor 
FROM 
   hierarchy 
WHERE descendant = :1 AND 
      ancestor IN (
                    SELECT 
                       distinct descendant 
                    FROM 
                       hierarchy WHERE ancestor = :2
                  )
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top