改进执行SQL / JOIN

时间:2013-10-15 22:13:27

标签: mysql sql join

我有2张桌子

表1列出了测试前的所有测试题。

表1:

testid  qnid    qn
1       1       currency of iran
1       2       highest peak        
1       3       longest bridge

表2列出了所有学生在测试后的测试状态:

表2:

studentid   testid  qnid    status  

    1       1       1       unanswered      
    1       1       2       unanswered  
    2       1       1       unanswered  
    2       1       2       answered    

给出的表2不完整,因为它不包含对所有qnid的响应。

结果应该是列出所有testid的表,qnid来自testnti的表1,来自表2的匹配testid,qnid for studentid = 2

即。结果:

testid  qnid    studentid    status     
1       1       2           unanswered
1       2       2           answered
1       3       

表2不包含表1中testid = 1 qnid = 3的值 在RESULT表中它的空格应该是空的。

我使用的查询:

select distinct table1.testid,table1.qnid,table2.status 
from table1 
  left outer join table2 
    on table1.testid = table2.testid 
where (table2.studentid = 2 
or table2.studentid =NULL)

但输出是:

testid  qnid    status
1       1       unanswered
1       1       answered
1       2       unanswered
1       2       answered
1       3       unanswered
1       3       answered

3 个答案:

答案 0 :(得分:1)

只需删除table2.studentid = NULL即可。

select distinct table1.testid,table1.qnid,table2.status 
from table1 
  left outer join table2 
    on table1.testid = table2.testid 
where table2.studentid = 2 

答案 1 :(得分:0)

你还需要加入问题ID ...所以你加入会是这样的:

table1 left outer join table2 on table1.testid = table2.testid AND table1.qnid = table2.qnid

答案 2 :(得分:0)

select distinct table1.testid,table1.qnid,coalesce(table2.student_id,NULL),table2.status 
from table1 
  left outer join table2 
    on table1.testid = table2.testid 
where table2.studentid = 2