views:

58

answers:

3

There is a scenario. There is an ask-and-answer website. An answerer can modify his answer, and the history of modification is saved on the server. Be default, only the latest version of each answer is displayed.

select * from answers where questionid='$questionid' group by answerer_id

So I can group all answers by answerer, then I need to select the latest version of each subgroup. How to achieve this?

A: 

If you are using autoincrement ids, you could select based on the highest id.

Possible SQL:

select * from answers where questionid='$questionid' 
    and id in (select max(id) from answers group by answerer_id)
Nathan Voxland
It is a solution.
Steven
What if I want to get the number of modifications in the meantime?
Steven
A: 

The GROUP BY clause seems to just use the first available row, so you could try using a sub-query to re-arrange them so the latest answer is on top.

SELECT * 
FROM (
    SELECT * FROM `answers`
    WHERE questionid='$questionid'
    ORDER BY answerer_id DESC
) as `dyn_answers` 
GROUP BY answerer_id
Atli
Do you meanSELECT * FROM ( SELECT * FROM `answers` WHERE questionid='$questionid' ORDER BY answer_id DESC) as `dyn_answers` GROUP BY answerer_id
Steven
That is exactly what I wrote, just without the back-ticks on the table names...
Atli
P.S., you can do `SELECT *, COUNT(answerer_id) as 'num_revisions'` to get the number of revisions.
Atli
+1  A: 

Do a self-join and find the user/question with no higher id:

SELECT a.*
FROM answers AS a
    LEFT JOIN answers AS b
    ON a.answerer_id = b.answerer_id
        AND a.question_id = b.question_id
        AND a.id < b.id
WHERE
    b.id IS NULL

Or, if you have a timestamp you can use that.

le dorfier