I have two tables: Foo and Bar. Foo contains the foreign key for the primary key Bar (bar_id). The bar is structured to allow the parent / child relationship through a foreign key (bar_parent_id) to another record in the bar. This ratio is limited so that any Bar record that has a parent cannot be a parent. However, any parent can have multiple children.
My request is to select all the entries in Foo that match the given entry in Bar, as well as any of the parents, children or siblings. The following is a query, but it is somewhat slow. Is there a way to structure it so that it works faster?
SELECT f.field1, f.field2
FROM Foo f
WHERE f.bar_id IN (
SELECT bar_id
FROM Bar
WHERE bar_id = @bar_id OR
bar_parent_id = @bar_id OR
bar_id = (SELECT bar_parent_id FROM Bar WHERE bar_id = @bar_id) OR
bar_parent_id = (SELECT bar_parent_id FROM Bar WHERE bar_id = @bar_id AND bar_parent_id > 0)
)
P.S. . , self/parent/child, Bar.