I have a table with an ID column, a parent ID column, and a foreign ID column so that some of the rows have child rows attached to them and each row is attached to a foreign key for grouping purposes. I want to say this at the outset since I've had issues with posts in the past. I'm not looking for comments on better table design, the table design is set and outside of my control and I'm just looking for some help dealing with what is already in place.
The issue is I'd like to query the table so that I can get the information for a group of rows and a column that shows whether or not that row is a "parent row". I have a query that works but its so slow that its almost useless even with fairly small datasets.
Here's the table design (let's call it table A)
A_Row_ID
A_Parent_ID
B_ForeignKey_ID
Information_Column
Here's the other table (let's call it Table B)
B_Row_ID
Here's the query I've come up with
SELECT A_2.A_Row_ID, A_2.Parent_ID, A_2.B_ForeignKey_ID, A_2.Information_Column.Member_ID,
CASE WHEN A_2.A_Row_ID IN
(SELECT DISTINCT A_2.A_Row_ID
FROM A INNER
JOIN B ON A.B_ForeignKey_ID = B.B_Row_ID INNER JOIN
A AS A_1 ON A.A_Row_ID= A_1.A_Parent_ID
WHERE (B.B_Row_ID = '1')) THEN 1 ELSE
0 END AS IsParent
FROM A_2 INNER JOIN
B ON A_2.B_ForeignKey_ID = B.B_Row_ID
WHERE (B.B_Row_ID = '1')
ORDER BY IsParent
Right now this query takes minutes to run when dealing with as few as 1000 rows. Any ideas where I can trim some time?