2012-12-07 59 views
5

我有兩個表,一個叫StudentCerts,包含一個電子郵件(主鍵)和一個證書,另一個叫CertReqs,包含一個證書和課程。表的一部分可能看起來像這樣:Tricky SQL加入查詢

 StudentCerts:         CertReqs:  
Email   Certificate    Certificate   Course 
[email protected]  Programmer   Programmer   CS 101 
[email protected]  English    Programmer   CS 202 
[email protected]   Econ     Programmer   CS 303 
[email protected]  Programmer   English    ENG 101 
             English    ENG 102 
             Econ     ECON 102 
             Econ     ECON 304 
             Art     Art 101 
             Art     Art 102 
             Journalism   J 101 
             Journalism   J 202 

我試圖做的就是讓所有的特定學生不是一部分的證書。例如,[email protected]註冊了程序員和英語證書,並且我希望獲得一個SQL語句,該語句將返回CertReq中的所有證書,該特定學生未註冊。因此,對於此示例它應該返回經濟,藝術和新聞。 我一直在努力爭取這一段時間,所以任何幫助將不勝感激!

回答

2
SELECT cr.Certificate FROM CertReqs cr 
WHERE cr.Certificate NOT IN (
    SELECT sc.Certificate FROM StudentCerts sc 
    WHERE sc.Email = '[email protected]' 
); 

查詢幾乎全文的要求:「我希望所有的CertReqs,用於該學生是不是在」。

+0

太謝謝你了!這正是我想要做的! – user1875195

0

這將列出所有的學生缺乏對某一證書

SELECT DISTINCT x.* 
FROM 
    (
     SELECT a.Email, b.Certificate 
     FROM (SELECT DISTINCT Email FROM StudentCerts) a 
       CROSS JOIN 
       (SELECT DISTINCT Certificate FROM CertReqs) b 
    ) x LEFT JOIN studentCerts y 
     ON x.Email = y.Email AND 
      x.Certificate = y.Certificate 
WHERE y.Email IS NULL 
ORDER BY x.EMAIL 

,如果你想爲特定的電子郵件,那麼你只需要添加額外的條件

SELECT DISTINCT x.* 
FROM 
    (
     SELECT a.Email, b.Certificate 
     FROM (SELECT DISTINCT Email FROM StudentCerts) a 
       CROSS JOIN 
       (SELECT DISTINCT Certificate FROM CertReqs) b 
    ) x LEFT JOIN studentCerts y 
     ON x.Email = y.Email AND 
      x.Certificate = y.Certificate 
WHERE y.Email IS NULL AND 
     x.Email = '[email protected]' 
ORDER BY x.EMAIL 
0
SELECT Certificate FROM `CertReqs` 

WHERE Certificate NOT in(
    SELECT Certificate 
    FROM `StudentCerts` 
    WHERE Email = '[email protected]' 
) 
1

在比賽中有點晚,但一個簡單的LEFT JOIN解決了這個問題非常好:

SELECT DISTINCT cr.Certificate 
FROM CertReqs cr 
LEFT JOIN StudentCerts sc ON cr.Certificate = sc.Certificate AND sc.Email = '[email protected]' 
WHERE sc.Email IS NULL 
0
SELECT DISTINCT A.* fROM 
(
SELECT DISTINCT EMAIL, CERTIFICATE fROM #StudentCerts A 
CROSS JOIN #CertReqs B) A 
LEFT JOIN #StudentCerts B ON A.EmaiL = B.EMAIL AND B.CERTIFICATES = A.Certificate 
WHERE B.EMAIL IS NULL 
ORDER BY A.EMAIL 
+2

歡迎來到Stack Overflow!儘管這段代碼可以解決這個問題,但[包括一個解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! – Machavity