您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在mysql中对左连接使用限制

在mysql中对左连接使用限制

从编辑和评论反馈中,这是我认为您正在寻找的查询…最内在的预查询获取帖子以及发起帖子,评论和发表评论的人员。此内部查询还与“最近的评论”一起在每个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之外的任何注释。

MySQL 2022/1/1 18:28:54 有263人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶