1

嗨,我正在尝试即兴发挥我的查询以获得更好的性能。是否有任何其他方式来编写我的 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; 
4

3 回答 3

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; 

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

于 2012-10-03T06:07:16.860 回答
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)
于 2012-10-03T09:11:20.143 回答
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; 
于 2012-10-03T21:40:14.010 回答