在MySQL的内部查询中使用外部查询的结果集

时间:2015-03-06 05:32:06

标签: mysql resultset correlated-subquery derived-table

我有两个名为"节点"和"链接"。我正在执行以下查询,它返回我想要的结果。如何优化这一个?我在内部查询中使用外部查询的结果集。如何在内部查询中引用外部查询的结果集,以防止再次运行相同的外部查询。箭头之间重复查询。

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 个答案:

答案 0 :(得分:0)

将执行效果不佳IN ( SELECT ... )变为加入。

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

- &GT;

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

并且看到至少有一个表格有INDEX(x)