【问题标题】:How to select the latest version of answers given by each answerer in MySQL?如何选择 MySQL 中每个回答者给出的最新版本的答案?
【发布时间】:2009-12-06 06:26:51
【问题描述】:

有一个场景。有一个问答网站。回答者可以修改他的回答,修改历史保存在服务器上。默认情况下,仅显示每个答案的最新版本。

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

所以我可以按回答者对所有答案进行分组,然后我需要选择每个子组的最新版本。如何做到这一点?

【问题讨论】:

  • MAX(date) 将获得最新的,但您需要提供有关 ANSWERS 表中列的更多详细信息。
  • 如果我想同时得到修改次数怎么办?

标签: php sql mysql group-by


【解决方案1】:

进行自加入并找到没有更高 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

或者,如果你有一个时间戳,你可以使用它。

【讨论】:

    【解决方案2】:

    GROUP BY 子句似乎只使用第一个可用行,因此您可以尝试使用子查询重新排列它们,以便最新答案位于顶部。

    SELECT * 
    FROM (
        SELECT * FROM `answers`
        WHERE questionid='$questionid'
        ORDER BY answerer_id DESC
    ) as `dyn_answers` 
    GROUP BY answerer_id
    

    【讨论】:

    • 你的意思是 SELECT * FROM (SELECT * FROM answers WHERE questionid='$questionid' ORDER BY answer_id DESC ) as dyn_answers GROUP BY answerer_id
    • P.S.,您可以通过SELECT *, COUNT(answerer_id) as 'num_revisions'获取修订数。
    【解决方案3】:

    如果您使用自动增量 id,您可以根据最高 id 进行选择。

    可能的 SQL:

    select * from answers where questionid='$questionid' 
        and id in (select max(id) from answers group by answerer_id)
    

    【讨论】:

    • 如果我想同时得到修改次数怎么办?
    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多