0

我有两个表用于在 MySQL 数据库上存储评论。

第一个存储评论 ID、发布评论的页面、评论的作者以及是否是对另一评论的回复(分别如下)。

Comments
---------------------------------
CommentId    BIGINT      PK,NN,AI
OwnerId      BIGINT      
AuthorId     BIGINT      
ParentId     BIGINT      
Created      TIMESTAMP   

第二个存储评论的内容。

CommentsContent
----------------------------------
ContentId    BIGINT      PK,NN,AI
CommentId    BIGINT      
Content      TEXT        
Created      TIMESTAMP   

所以,假设Comments有以下记录:

CommentId  OwnerId  AuthorId  ParentId  Created
-----------------------------------------------------------
        1        1         2         0  2013-01-31 01:23:45
        2        1         2         0  2013-01-31 01:23:45

并且CommentsContent有以下记录,显示评论的编辑历史:

ContentId  CommentId  Content           Created
-----------------------------------------------------------
        1          1  Testing           2013-01-31 01:23:45
        2          2  Another test      2013-01-31 01:23:45
        3          1  Testing1          2013-01-31 01:23:46
        4          1  Testing123        2013-01-31 01:23:47

现在,我想获取最新评论以及它的最后更新日期(即 中的CreatedCommentsContent)。

我试过:

SELECT
    c.CommentId,
    c.AuthorId,
    c.ParentId,
    c.Created,
    cc.Created as Updated,
    cc.Content
FROM
    Comments as c
JOIN
    CommentsContent as cc
ON
    cc.CommentId = c.CommentId
WHERE
    c.OwnerId = 1

不幸的是,这会返回所有行,并预先CommentsContent加上它们的数据。Comments

我正在寻找以下输出:

 CommentId  AuthorId  ParentId  Created              Updated              Content
 -------------------------------------------------------------------------------------
         1         2         0  2013-01-31 01:23:45  2013-01-31 01:23:47  Testing123
         2         2         0  2013-01-31 01:23:45  2013-01-31 01:23:45  Another test

这在单个查询中是否可能而不嵌入嵌套的SELECT. 我需要使用GROUP从句吗?不过,我听说GROUP子句的性能很差。我应该创建一些额外的索引来帮助加快GROUP子句的速度吗?

感谢您的输入!

4

1 回答 1

1

不幸的是,MySQL 没有像 SQL Server 和其他一些窗口函数。因此,您需要为此使用子查询:

SELECT
    c.CommentId,
    c.AuthorId,
    c.ParentId,
    c.Created,
    cc.Created as Updated,
    cc.Content
FROM Comments as c
JOIN CommentsContent as cc
  ON cc.CommentId = c.CommentId
INNER JOIN
(
  select max(created) MaxDate, commentid
  from CommentsContent
  group by commentid
) cc2
  on cc.created = cc2.maxdate
  and cc.commentid = cc2.commentid
WHERE c.OwnerId = 1

请参阅带有演示的 SQL Fiddle

于 2013-01-31T23:30:36.417 回答