在mySQL中选择不同三元组的补充

时间:2012-06-28 00:19:21

标签: mysql sql database

我有这两个表

test_table
date        student     test
2012-05-31  Alice       Math
2012-05-31  Alice       Math
2012-05-31  Bob         Math
2012-05-31  Bob         Spelling
2012-06-01  Alice       Math
2012-06-01  Alice       Spelling

score_table
date        student     test        best_daily_score
2012-05-31  Alice       Math        90
2012-05-31  Bob         Math        50
2012-05-31  Bob         Spelling    50
2012-06-01  Alice       Math        95

我想检测到best_daily_scoreSpelling2012-06-01测试的2012-06-01 Alice Spelling 尚未记录。我正在寻找返回

的查询
SELECT DISTINCT date, student, test FROM test_table

这是

的唯一一行
SELECT DISTINCT date, student, test FROM score_table

不在

SELECT DISTINCT date, student, test FROM test_table WHERE date, student, test NOT IN (SELECT DISTINCT date, student, test FROM score_table)

这不起作用:

NOT IN

我假设因为{{1}}的左侧不应该是三件事的列表。

1 个答案:

答案 0 :(得分:5)

尝试一下:

SELECT  a.date,
        a.student,
        a.test
  FROM  test_table a 
          LEFT JOIN score_table b
            ON (a.date = b.date) AND
               (a.student = b.student) AND
               (a.test = b.test)
WHERE   b.best_daily_score IS NULL

由于test_table,查询会尝试匹配score_tableLEFT JOIN的所有记录是否存在。它与datestudenttest匹配。如果在score_table上找不到记录,那么基本上best_daily_score将是NULL。这就是为什么我添加了一个条件,只在NULL上显示best_daily_score

<强> Click Here for some DEMO (SQLFiddle)