2012-10-03 99 views
1

您好我正在試圖即興我的查詢來獲得更好的performance.Is任何其他方式寫我的SQL.The問題如下。調整我的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; 
+0

什麼是cid?啊,似乎是course_id –

+0

是的cid是課程編號 – Teja

回答

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; 

子查詢將返回部門,以及類標識碼組安德魯,然後查詢將得到所有的學生具有相同的規格。

+0

感謝您的答案。我如何在Tuple關係演算中編寫相同的查詢?任何見解? – Teja

+0

首先,我在很多年前完成了CS,我的思想受到了一種名爲遺忘的機制的保護。其次,你應該做你的作業。 –

+0

當然,'S'中沒有'cid'。 –

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) 
+0

謝謝;)沒有注意到 – Deceiver

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;