调整我的SQL查询

时间:2012-10-03 05:05:23

标签: sql oracle performance

您好我正在尝试即兴创建我的查询以获得更好的性能。还有其他任何方式来编写我的SQL。问题如下。

SELECT DISTINCT A.name as name,
                A.gender as gender
FROM 
(
SELECT *  
 FROM Students S,
      Enrollment E,
      Group1 G,
      Ingroup I   
 WHERE S.sid = E.sid 
   AND S.sid = I.sid
   AND I.gid = G.gid 

)A,
(SELECT *
 FROM Students S,
      Enrollment E,
      Group1 G,
      Ingroup I   
 WHERE S.sid = E.sid 
   AND S.sid = I.sid
   AND I.gid = G.gid 
   AND S.name="Andrew Peers"
) B
WHERE A.dept = B.dept
  AND A.cid  = B.cid
  AND A.gid  = B.gid; 

3 个答案:

答案 0 :(得分:1)

两个子查询返回太多行。我不知道你的表之间的结构和关系,所以,我所能做的就是减少第二次查询的行数。 还使用ANSI连接语法:

SELECT S.name as name,
       S.gender as gender
FROM Students S
      JOIN Enrollment E ON S.sid = E.sid 
      JOIN Ingroup I on  S.sid = I.sid
      JOIN Group1 G on I.gid = G.gid
      JOIN 
         (SELECT dept, cid, gid
          FROM Students S
            JOIN Enrollment E ON S.sid = E.sid 
            JOIN Ingroup I on  S.sid = I.sid
            JOIN Group1 G on I.gid = G.gid
          WHERE S.name="Andrew Peers"
         GROUP BY dept, cid, gid
        ) B 
        ON S.dept = B.dept AND G.cid  = B.cid AND G.gid  = B.gid; 

子查询将返回部门,class_id和Andrew组,然后查询将获得具有相同规格的所有学生。

答案 1 :(得分:0)

首先在from中构建子查询是不好的,因为丢失了索引,降低了性能。 我不确定,但我没有看到需要使用所有4个表,检查我离开的这个查询是否符合您的目的:

    Select distinct S.name AS name, 
           S.gender AS gender
      from Students S,
           Group1 G,
           Ingroup I
     where 1=1
       AND S.sid   = I.sid
       AND I.gid   = G.gid
       and exists (select 'X'
                     from Students S1
                        , Ingroup I1
                    where 1=1
                      and S1.sid   = I1.sid
                      and I1.gid = I.gid
                      and S1.sid = S.sid)

答案 2 :(得分:0)

只是想法......

WITH (SELECT *
 FROM Students S,
      Enrollment E,
      Group1 G,
      Ingroup I   
 WHERE S.sid = E.sid 
   AND S.sid = I.sid
   AND I.gid = G.gid 
   AND S.name="Andrew Peers"
) Andrew
SELECT A.name as name,
                A.gender as gender

 FROM Students S,
      Enrollment E,
      Group1 G,
      Ingroup I   
 WHERE S.sid = E.sid 
   AND S.sid = I.sid
   AND I.gid = G.gid 

   AND g.gid = Andrew.gid
   AND e.cid = Andrew.cid
   AND s.dept = Andrew.dept;