5

我有两张表,一张名为 StudentCerts,包含电子邮件(主键)和证书,另一张名为 CertReqs,包含证书和课程。表格的一部分可能如下所示:

     StudentCerts:                                 CertReqs:    
Email           Certificate             Certificate          Course
This@that.com      Programmer            Programmer           CS 101
This@that.com      English               Programmer           CS 202
A@B.com            Econ                  Programmer           CS 303
john@smith.com     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

我想要做的是获得特定学生不属于的所有证书。例如,This@that.com 注册了程序员和英语证书,我想获得一条 SQL 语句,它将返回 CertReqs 中特定学生未注册的所有证书。所以对于这个例子它应该返回 Econ、Art 和 Journalism。我一直在努力得到这个,所以任何帮助将不胜感激!

4

5 回答 5

2
SELECT cr.Certificate FROM CertReqs cr
WHERE cr.Certificate NOT IN (
    SELECT sc.Certificate FROM StudentCerts sc
    WHERE sc.Email = 'This@that.com'
);

该查询几乎读作要求:“我想要所有 CertReqs,学生不在其中”。

于 2012-12-07T07:29:06.500 回答
1

游戏有点晚了,但是一个简单的LEFT JOIN方法很好地解决了这个问题:

SELECT DISTINCT cr.Certificate 
FROM CertReqs cr
LEFT JOIN StudentCerts sc ON cr.Certificate = sc.Certificate AND sc.Email = 'This@that.com'
WHERE sc.Email IS NULL
于 2012-12-07T07:51:56.820 回答
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 = 'This@that.com'
ORDER BY x.EMAIL
于 2012-12-07T07:30:06.877 回答
0
SELECT Certificate FROM `CertReqs` 

WHERE Certificate NOT in(
    SELECT Certificate 
    FROM `StudentCerts` 
    WHERE Email  = 'This@that.com' 
)
于 2012-12-07T07:44:57.053 回答
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 
于 2017-07-31T12:56:06.350 回答