结果无法理解sql查询

时间:2014-06-18 10:25:09

标签: sql

我有编写查询Sql的另一个问题 我有两张桌子: candidat_test_answerand和answer,格式如下。

id_question || id_answer  ||id_test || id_candidat || date

|  1        ||  1         ||17      ||     1       ||2014-06-01
|  1        ||  2         ||17      ||     1       ||2014-06-01
|  3        ||  NULL      ||17      ||     1       ||2014-06-01
|  1        ||  7         ||18      ||     1       ||2014-06-03

id_answer   || choice_answer   || correct|| id_question     
|  1        ||  2              ||  1     ||     1      
|  2        ||  5              ||  0     ||     1       
|  3        ||  6              ||  0     ||     1           
|  4        ||  7              ||  0     ||     1     
|  5        ||  3              ||  0     ||     2         
|  6        ||  1              ||  0     ||     2     
|  7        ||  xxx            ||  1     ||     3  
|  8        ||  ttt            ||  0     ||     3      


select id_question,id_answer,choice_answer,correct,id_test,id_candidat,date from    candidat_test_reponse ctr  left join answer p  on  ID_cand=1 and ID_Test=17 and  p.ID_answer=ctr.ID_onswer and ctr.date='2014-06-01'  

我的查询显示

id_question || id_answer  || choice_answer ||correct ||id_test || id_candidat || date
|  1        ||  1         ||   1           ||    1   ||17      ||     1       ||2014-06-01
|  1        ||  2         ||    2          ||    0   ||17      ||     1       ||2014-06-01
|  3        ||  NULL      ||               ||        ||17      ||     1       ||2014-06-01
|  1        ||  7         ||               ||    1   ||18      ||     1       ||2014-06-03

我不明白那条线(在我的查询中我有这个条件ctr.date ='2014-06-01和ID_Test = 17)

|  1        ||  7         ||               ||    1   ||18      ||     1       ||2014-06-03

1 个答案:

答案 0 :(得分:0)

您的查询是:

select id_question,id_answer,choice_answer,correct,id_test,id_candidat,date
from candidat_test_reponse ctr  left join
     answer p 
     on  ID_cand=1 and ID_Test=17 and  p.ID_answer=ctr.ID_onswer and ctr.date='2014-06-01'  

你正在做left join。这意味着无论条件是否为真,查询都会将所有内容保留在第一个表中。这适用于第一个表格和第二个表格的条件。

您可以将join更改为inner join以进行所需的过滤:

select id_question, id_answer, choice_answer, correct, id_test, id_candidat, date
from candidat_test_reponse ctr inner join
     answer p 
     on  ID_cand=1 and ID_Test=17 and  p.ID_answer=ctr.ID_onswer and ctr.date='2014-06-01'  

或者,您的意图可能是:

select id_question, id_answer, choice_answer, correct, id_test, id_candidat, date
from candidat_test_reponse ctr left join
     answer p 
     on  ID_cand = 1 and p.ID_answer = ctr.ID_onswer
where ID_Test = 17 and ctr.date = '2014-06-01' ;