- I have 3 hierarchical tables. [Parent] ->[Child1]->[Child2]
- I have [Xref] table which stores the documents associated with these three tables. In the [Xref] table, the column “TypeID” defines to which table the document is associated with.
- Below is the table structure with some sample data.
Question: Given parented I want to get all the documents associated with parent as well its children. My sql query uses Union and its working fine. But Is there any other simple way to re-write this query?
(Note that this is just an example, the actual hierarchy is pretty long so my SQL is getting little messy and I want simplify it.)
TYPES TypeID TypeName ----------------------------------------- 1 Parent 2 Child1 3 Child2 TABLE - PARENT ParentID ------------------------------------- 1 2 3 TABLE - CHILD1 Child1ID ParentID ---------------------------------------- 1 1 2 1 3 2 TABLE - CHILD2 Child2ID Child1ID -------------------------------------------- 1 1 2 1 3 2 4 2 XREF DocumentID TypeID LocatorID ------------------------------------------ 1 1 1 2 1 2 3 1 3 4 2 1 5 2 2 6 2 3 7 3 1 8 3 2 9 3 3 10 3 4
SELECT DocumentID FROM XREF X JOIN Parent P ON P.ParentID = x.LocatorID AND TypeID = 1 -- Parent WHERE P.ParentID = @ParentID UNION SELECT DocumentID FROM XREF X JOIN Child1 C1 ON C1.Child1ID = x.LocatorID AND TypeID = 2 -- Child1 JOIN Parent P ON P.ParnetID = C1.ParentID WHERE P.ParentID = @ParentID UNION SELECT DocumentID FROM XREF X JOIN Child2 C2 ON C2.Child1ID = x.LocatorID AND TypeID = 3 -- Child2 JOIN Child1 C1 ON C1.Child1ID = c2.Child1ID JOIN Parent P ON P.ParnetID = C1.ParentID WHERE P.ParentID = @ParentID