小编典典

在mysql中对左连接使用限制

sql

以下查询选择所有帖子和每个帖子的所有者,属于每个帖子的所有评论以及每个评论的所有者。

我只需要每个帖子检索5条评论。我重写了查询,但是收到“每个派生表必须具有它自己的别名”的错误。

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname, comments.id AS commentId, comments.text, commenters.id, commenters.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN comments ON posts.id = comments.postid
    JOIN users AS commenters ON comments.userId = commenters.id
ORDER BY posts.createdAt

新查询:

SELECT posts.id AS postId, posts.body, users.id AS userId, users.displayname
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN (
    SELECT comments.id AS commentId, comments.text AS commentText, commenters.id AS commenterId, commenters.displayname AS commenterDisplayName
    FROM comments
    JOIN users AS commenters ON comments.userid = commenters.id
    LIMIT 0,5
        ) AS comments ON comments.postid = posts.id
ORDER BY posts.createdAt

更新 查询现在可以使用,但不会产生所需的输出。我想输出10个帖子,每个帖子有5条评论。该限制条款仅适用于遇到的第一篇文章的评论。


阅读 293

收藏
2021-04-22

共1个答案

小编典典

从编辑和评论反馈中,这是我认为您正在寻找的查询…最内在的预查询将获取帖子以及发起帖子,评论和发表评论的人员。此内部查询还与“最近的评论”一起在每个postID的顶部进行了预排序。使用该结果,我将加入sql变量(@variables),以使@varRow在每次添加新注释时增加,并在每次帖子ID更改时重置为1(因此,通过帖子ID
FIRST发出的内部PreQuery顺序)。最后,使用HAVING子句使评论的@varRow计数<6将获得每个帖子的MOST 5。

如果要限制尝试检索的帖子,我将在生成“ PreQuery”的最内处应用WHERE子句(例如日期/时间,如果可用)。

select straight_join
      PreQuery.*,
      @varRow := if( @LastPost = PreQuery.PostID, @varRow +1, 1 ) CommentRow,
      @LastPost := PreQuery.PostID PostID2
   from
      ( select
              posts.id PostID,
              posts.body,
              posts.CreatedAt,
              u1.id UserID,
              u1.DisplayName NameOfPoster,
              c.id,
              c.userid CommentUserID,
              c.text CommentText,
              u2.DisplayName CommentUserName
           from
              posts
                 join users u1
                    on posts.ownerUserID = u1.id

                 LEFT JOIN comments c
                    on posts.id = c.PostID

                    join users u2
                       on c.userid = u2.id 
            where
                  posts.id = TheOneParentIDYouWant
               OR posts.parentid = TheOneParentIDYouWant
            order by
               posts.ID,
               c.id desc ) PreQuery,

      (select @varRow := 0, @LastPost = 0 ) SQLVars

   having
      CommentRow < 6

   order by
      PreQuery.postid,
      CommentRow

-–编辑—
每个评论我认为您与评论关联的“父帖子”的含义是因为它们直接具有帖子ID。由于最里面的查询会全面连接所有元素/表,因此所有这些元素/表都将随之而来…

Post -> User (to get posting user name )
Post -> Comment (on Common Post ID -- left joined)
        Comment -> User ( to get commenting user name)

一旦完成所有操作并按通用的帖子ID进行排序,并且将最新注释排序到顶部,则对所有返回的行应用@vars。HAVING子句会去除序列中以您要查找的5之外的任何注释。

2021-04-22