2016-02-28 104 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

謝謝戈登! –