如何在MySQL中选择最后编辑的帖子版本?

时间:2018-05-14 13:04:25

标签: mysql sql

这是我的表结构:

// posts
+----+-----------------------------+-----------+------------+
| id |            body             | edited_id | date_time  |
+----+-----------------------------+-----------+------------+
| 1  | post1                       | NULL      | 1464136759 |
| 2  | post2                       | NULL      | 1464136760 | 
| 3  | post2     edited            | 2         | 1464136761 | 
| 4  | post2     eduted again      | 2         | 1464136762 | 
+----+-----------------------------+-----------+------------+

如您所见,上表保留了帖子及其版本。目前我正在选择这样的帖子:

SELECT * FROM posts WHERE id IN (1,2) ORDER BY date_time ASC;

当前输出:

| 1  | a question                  | NULL      | 1464136759 |
| 2  | my answer                   | NULL      | 1464136760 | 

预期输出:

| 1  | a question                  | NULL      | 1464136759 |
| 4  | my answer eduted again      | 2         | 1464136762 | 

见?帖子id = 2有两个版本,我总是需要选择最大版本(根据date_time)。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

如果未对行进行编辑,则可以使用:

select p.*
from posts p
where (p.id in (1, 2) or p.edited_id in (1, 2)) and
      p.id = (select p2.id
              from posts p2
              where p.id in (p2.id, p2.edited_id)
              order by date_time desc
              limit 1
             );