mysql使用子查询改进视图

时间:2013-04-09 02:51:10

标签: mysql performance subquery mysql-error-1349

我需要比较同一列中的行,所以我有以下mysql查询,它可以很好地给出预期的结果。

SELECT x.aord, 
       x.anode AS parent, 
       x.bnode AS child 
FROM   (SELECT a.ordinal               AS aord, 
               a.id_dt_graph_node_edge AS aid, 
               a.id_dt_graph_node      AS anode, 
               b.ordinal               AS bord, 
               b.id_dt_graph_node_edge AS bid, 
               b.id_dt_graph_node      AS bnode 
        FROM   dt_graph_node_edge a 
               JOIN dt_graph_node_edge b 
                 ON a.ordinal < b.ordinal) x 
       LEFT JOIN (SELECT a.ordinal               AS aord, 
                         a.id_dt_graph_node_edge AS aid, 
                         a.id_dt_graph_node      AS anode, 
                         b.ordinal               AS bord, 
                         b.id_dt_graph_node_edge AS bid, 
                         b.id_dt_graph_node      AS bnode 
                  FROM   dt_graph_node_edge a 
                         JOIN dt_graph_node_edge b 
                           ON a.ordinal < b.ordinal) y 
              ON x.aord = y.aord 
                 AND x.bord > y.bord 
WHERE  y.bord IS NULL 
ORDER  BY x.aord, 
          x.bord 

我发现由于错误#1349,无法在此查询上创建视图。任何人都可以提出更好的方法来进行此类查询,特别关注速度,实际上这个查询非常慢。感谢。

1 个答案:

答案 0 :(得分:0)

您无法从查询中创建VIEW的原因是因为它包含子查询。根据文档,VIEW不能在SELECT查询中包含子查询。解决方法是首先在子查询上创建VIEW,例如

CREATE VIEW firstSubquery
AS
SELECT a.ordinal               AS aord, 
       a.id_dt_graph_node_edge AS aid, 
       a.id_dt_graph_node      AS anode, 
       b.ordinal               AS bord, 
       b.id_dt_graph_node_edge AS bid, 
       b.id_dt_graph_node      AS bnode 
FROM   dt_graph_node_edge a 
       JOIN dt_graph_node_edge b 
         ON a.ordinal < b.ordinal;

CREATE VIEW secondSubquery
AS
SELECT  a.ordinal               AS aord, 
        a.id_dt_graph_node_edge AS aid, 
        a.id_dt_graph_node      AS anode, 
        b.ordinal               AS bord, 
        b.id_dt_graph_node_edge AS bid, 
        b.id_dt_graph_node      AS bnode 
FROM   dt_graph_node_edge a 
        JOIN dt_graph_node_edge b 
        ON a.ordinal < b.ordinal;

并在当前查询

上加入新创建的VIEW
CREATE VIEW finalVIEW
AS
SELECT x.aord, 
       x.anode AS parent, 
       x.bnode AS child 
FROM   firstSubquery x 
       LEFT JOIN secondSubquery y 
              ON x.aord = y.aord AND x.bord > y.bord 
WHERE  y.bord IS NULL 
ORDER  BY x.aord,  x.bord 

PS:MySQL中的VIEWS非常糟糕