0

I have two tables called "nodes" and "links". I am performing the following query and it returns the results I want. How to optimize this one? I am using the resultset of the outer query in inner query. How to reference to the resultset of the outer query in inner queries so as to prevent running the same outer query again. Repeated queries between arrows.

SELECT * FROM nodes where name = 'Compost' union all 
-> SELECT * FROM nodes where id in
 ( SELECT target from links where source in 
    ( SELECT id FROM  (SELECT * FROM nodes where name = 'Compost' <- ) as a)) union all  SELECT * FROM nodes where id in 
        ( SELECT target from links where source in (SELECT id FROM (   -> SELECT * FROM nodes where id in ( SELECT target from links where source in 
            ( SELECT id FROM (SELECT * FROM nodes where name = 'Compost'<- ) as c))) as b))

1 Answers1

0

Turn IN ( SELECT ... ), which performs poorly, into JOIN.

SELECT  ...
    FROM  a
    WHERE  x IN (
        SELECT  x
            FROM  b
            WHERE  test_b 
                )
      AND  test_a; 

-->

SELECT  ...
    FROM  a
    JOIN  b USING(x)
    WHERE  test_a
      AND  test_b;

And see that you have INDEX(x) on at least one of the tables.

Rick James
  • 135,179
  • 13
  • 127
  • 222