2016-02-28 138 views
0

我有一个表userSection(问表),其具有userSectionId,我也可以在任何的答案表isee_answers_2013isee_answers_2014isee_answers_2015isee_answers_2016的相应的答案。目前查询已经是识别匹配从表中的记录

select us.userSectionId,qs.questionSectionId,qs.questionId,us.userId, 
case 
when a13.correct is not null then a13.answerId 
when a14.correct is not null then a14.answerId 
when a15.correct is not null then a15.answerId 
when a16.correct is not null then a16.answerId 
end 
as AnswerId, 
case 
when a13.correct is not null then a13.correct 
when a14.correct is not null then a14.correct 
when a15.correct is not null then a15.correct 
when a16.correct is not null then a16.correct 
end 
as Correct, 
case 
when a13.correct is not null then a13.duration 
when a14.correct is not null then a14.duration 
when a15.correct is not null then a15.duration 
when a16.correct is not null then a16.duration 
end 
as Duration 
from userSections us 
join questionSections qs on qs.sectionId = us.sectionId 
JOIN 
    userExams ue 
ON 
    ue.userExamId = us.userExamId 
left join 
isee_answers_2013.answers a13 on us.userSectionId=a13.userSectionId and us.UserId = a13.userId 
left join 
isee_answers_2014.answers a14 on us.userSectionId=a14.userSectionId and us.UserId = a14.userId 
left join 
isee_answers_2015.answers a15 on us.userSectionId=a15.userSectionId and us.UserId = a15.userId 
left join 
isee_answers_2016.answers a16 on us.userSectionId=a16.userSectionId and us.UserId = a16.userId 
WHERE 
    us.valid=1 and ue.userExamId=20467 

可能有人请验证,并说,如果这是正确的做法或有没有这样做的任何其他更好的办法?

回答

2

假设这个逻辑是正确的,你可能只需要使用coalesce()

coalesce(a13.answerId, a14.answerId, a15.answerId, a16.answerId) as answerId 

等。

逻辑不是恰好与相同。如果answerId在匹配的答案上可以是NULL,那么这不会做你想要的。否则,这是表达这种逻辑的一种更简单的方式。

+0

谢谢戈登! –