Search code examples
sql-serverdatabase-table

Getting the last answer id for the questions


In M.C.Q test, when user come back to the same question again how can I track the last answer given for the question?,

following is the table structure

Method: 1    
temptblUserAnswer
    id   uid   qid   ansid
    1    1     1     5
    2    1     2     6

Should I update the table value for that particular Question?
OR
Should I use following table structure?

Method: 2    
temptblUserAnswer
    id   uid   qid   ansid   timestamp
    1    1     1     5       2011-09-28 11:54:32
    2    1     2     12      2011-09-28 11:58:40
    3    1     1     7       2011-09-28 12:02:50

Here with the help of timestamp I can find the the last answer for any particular question.

Now the question is, which method to follow, and which will be performance oriented?
Or any better suggestion for the same? Should I go with Method:1 and apply the index on uid, ansid column?


Solution

  • If your Id is autoincrementing, you can get last answer based on Id:

    SELECT TOP 1 AnsID
    WHERE Uid=@UserId AND Qid=@QuestionID
    ORDER BY Id DESC
    

    About performance:you should put non-clustered index on Uid AND Qid AND ID and Include AnsID

    You can avoid of using timestamp column in this table.