棘手的SQL加入查询

时间:2012-12-07 07:24:38

标签: mysql sql join

我有两个表,一个名为包含电子邮件(主键)和证书的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中特定学生未注册的所有证书。所以对于这个例子它应该归还经济,艺术和新闻。 我一直在努力争取这个,所以任何帮助都会非常感激!!

5 个答案:

答案 0 :(得分: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,学生不在其中”。

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

SELECT Certificate FROM `CertReqs` 

WHERE Certificate NOT in(
    SELECT Certificate 
    FROM `StudentCerts` 
    WHERE Email  = 'This@that.com' 
)

答案 4 :(得分: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