2012-06-28 48 views
1

我有表像這兩個選擇不同的三元組的補充在MySQL的

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 

我想檢測Alice的best_daily_scoreSpelling測試上2012-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) 

我假設是因爲的左側不應該是三件事情的清單。

回答

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_table它是否存在或LEFT JOIN不是因爲。它匹配date,studenttest。如果在score_table上找不到記錄,那麼基本上best_daily_score將是NULL。這就是爲什麼我在best_daily_score上添加了一個僅顯示NULL的條件。

Click Here for some DEMO (SQLFiddle)