mysql 关联 table 上的外部联接(未选择)

mysql outer join (unselected) on assosiative table

我有3个table = 'Test','Test_quo','Subject'

Table 测试

idtest | Test
1      | Test wave 1
2      | Test Wave 2

Table Test_quo

idtest | idsubject
1      | 1
1      | 2
1      | 3
2      | 1

Table 主题

  idsubject| subject
    1      | Math
    2      | Bio
    3      | Sport
    4      | Literature

我需要的是 select 外部(未select在某些测试中的主题), 例如,在 idtest=1 上,结果将是 literature

 idsubject | subject
    4      | Literature

我已经尝试过使用 left, outer 并没有达到预期的结果 (selected/choosen) subject.

SELECT subject.idsubject, subject FROM subject right OUTER JOIN test_quo ON (subject.idsubject = test_quo.idsubject) where test_quo.idtest=1'

我的查询会得到结果

idsubject | subject
       1  | Math
       2  | Bio
       3  | Sport

我相信你需要像下面这样的东西。它将为您提供所有测试的 "unselected" 个科目。

SELECT subject.idsubject, subject 
FROM subject 
LEFT OUTER JOIN test_quo ON (subject.idsubject = test_quo.idsubject) 
WHERE ISNULL(test_quo.idsubject) 

DEMO

仅针对 idtest=1 我想出了以下相关 sub-query:

SELECT s.idsubject, subject 
FROM subject s
WHERE NOT EXISTS (SELECT 1 
                  FROM test_quo t 
                  WHERE s.idsubject = t.idsubject AND t.idtest = 1)

Another Demo

并且(最终)与 OUTER JOIN 相同:

SELECT subject.idsubject, subject 
FROM subject 
LEFT OUTER JOIN test_quo ON (subject.idsubject = test_quo.idsubject AND test_quo.idtest = 1)
WHERE ISNULL(test_quo.idsubject) 

Demo with one more subject