How to make this subqueries to good-looking code? And I looking guides about SQL optimization and code style.
SELECT foo FROM table WHERE foo_id IN
(
SELECT idchild FROM table2 WHERE idparent IN
(SELECT idchild FROM table2 WHERE idparent IN
(SELECT idchild FROM table2 WHERE idparent = @id)
))
AND txt_type ='some_cat'
For better performance and readability, do this:
Notice how the first table selected from has an indexed predicate in the where clause. This query will use indexed access all the way through the query and be very efficient.
Also notice how I moved the predicate for txt_type into the
onclause, where it can be applied at the time the row is read, rather than after the joins have been assembled.