I have a table (MainTable
) with a bit over 600,000 records. It joins onto itself via a 2nd table (JoinTable
) in a parent/child type relationship:
Try this one. Same result, different approach:
SELECT c.ID, p.ID
FROM
(SELECT Child.ID, JoinTable.ParentID
FROM MainTable
AS Child
JOIN JoinTable
ON Child.ID = JoinTable.ID) AS c
INNER JOIN
(SELECT Parent.ID, JoinTable.ID
FROM MainTable
AS Parent
JOIN JoinTable
ON Parent.ID = JoinTable.ParentID
AND Parent.SomeOtherData = Child.SomeOtherData) AS p
ON c.ParentID = p.ID
If it does not help, use cte:
;WITH cte AS
(SELECT Child.ID, JoinTable.ParentID
FROM MainTable
AS Child
JOIN JoinTable
ON Child.ID = JoinTable.ID)
SELECT cte.ID, Parent.ID
FROM cte INNER JOIN
MainTable
AS Parent
ON Parent.ID = cte.ParentID
AND Parent.SomeOtherData = cte.SomeOtherData