如何在不知道我们需要多少行的情况下控制SQL查询中返回行的数量

时间:2015-04-06 20:35:09

标签: sql sql-server

我们说我有一个posts表和一个comments表。我想从我的数据库中获取前两个帖子,以及随之而来的所有评论。 SQL查询可能如下所示:

SELECT C.CommentId, P.PostId FROM Post AS P
    LEFT JOIN Comment AS C ON P.PostId = C.PostId
    ORDER BY P.PostId ASC
    OFFSET 0 ROWS FETCH NEXT 6 ROWS ONLY

这给了我这个回归集:

PostId CommentId
1      1
1      2
1      3
2      1
2      2
2      3

而不是硬编码" 6"在FETCH NEXT 6 ROWS中,如何以这样的方式编写查询:无论P.PostId值是什么,我都会获取数据库中前两个帖子的所有相关注释?

5 个答案:

答案 0 :(得分:4)

在下面添加带星号的行。

SELECT C.CommentId, P.PostId FROM Post AS P
LEFT JOIN Comment AS C ON P.PostId = C.PostId
**where p.postID in (select top 2 postID from post order by postID)**
ORDER BY P.PostId ASC

答案 1 :(得分:4)

;WITH CTE AS (
SELECT C.CommentId
     , P.PostId 
     , DENSE_RANK() OVER (ORDER BY P.PostId  ASC) rn 
FROM Post AS P
LEFT JOIN Comment AS C ON P.PostId = C.PostId
)
SELECT CommentId
      ,PostId
FROM CTE 
ORDER BY PostId ASC
WHERE rn <= 2

或者

SELECT CommentId
      ,PostId
FROM
 (
SELECT C.CommentId
     , P.PostId 
     , DENSE_RANK() OVER (ORDER BY P.PostId  ASC) rn 
FROM Post AS P
LEFT JOIN Comment AS C ON P.PostId = C.PostId
ORDER BY P.PostId ASC
) A
WHERE rn <= 2
ORDER BY PostId ASC

答案 2 :(得分:1)

根据您的问题陈述

而不是硬编码&#34; 6&#34;在FETCH NEXT 6 ROWS中,我如何以这样的方式编写查询:无论P.PostId值是什么,我都会获得数据库中前两个帖子的所有相关注释?

将此查询包装到存储过程中并提供以下三个参数,而不是硬编码OFFSETROWSTop

Declare @offset int 
Declare @rows int
Declare @top int

 with cte as 
 (
   SELECT TOP (@top) postID 
   FROM post 
    ORDER BY postID 
) 

    SELECT C.CommentId, P.PostId 
    FROM Post AS P
    LEFT JOIN Comment AS C ON P.PostId = C.PostId
    WHERE  p.postID in (select postID from cte)
    ORDER BY P.PostId ASC
    OFFSET @offset ROWS FETCH NEXT @rows ROWS ONLY

答案 3 :(得分:0)

这个怎么样?只是想在这里“脱掉袖口”......这还没有经过测试。

SELECT C.CommentId, P.PostId FROM Post AS P
    LEFT JOIN Comment AS C ON P.PostId = C.PostId
    WHERE P.PostId > P.PostId-2
    ORDER BY P.PostId ASC

答案 4 :(得分:-2)

SELECT **top 2**
 C.CommentId, P.PostId FROM Post AS P
    LEFT JOIN Comment AS C ON P.PostId = C.PostId
    ORDER BY P.PostId ASC
    OFFSET 0 ROWS FETCH NEXT 6 ROWS ONLY