SQL ROW_NUMBER()...在x和y之间断开内部连接

时间:2013-09-25 21:10:23

标签: sql sql-server tsql inner-join custompaging

我有这个内部连接语句,大部分都有效,但是当我添加自定义分页时,连接返回一个空集。任何建议将不胜感激。

这会返回我期望的结果

SELECT [Id]
,[Title]
FROM 
(SELECT [Id]
,[Title]
,ROW_NUMBER() OVER(ORDER BY id) as RowNum from Art) as e
INNER JOIN [ArtCat] p ON e.Id = p.ArtId 
WHERE 
p.CatId = @CategoryNum

这将返回一个空集

SELECT [Id]
,[Title]
FROM 
(SELECT [Id]
,[Title]
,ROW_NUMBER() OVER(ORDER BY id) as RowNum from Art) as e
INNER JOIN [ArtCat] p ON e.Id = p.ArtId 
WHERE 
p.CatId = @CategoryNum
AND  RowNum BETWEEN @startIndex AND (@startIndex + @pageSize) 

提前致谢!

2 个答案:

答案 0 :(得分:0)

格式化有点难以阅读,但语法很好,为什么不检查rownum的界限:

SELECT MIN(RowNum),MAX(RowNum)          
FROM (SELECT [Id]
            ,[Title]
            ,ROW_NUMBER() OVER(ORDER BY id) as RowNum 
      FROM Art
      ) as e
INNER JOIN [ArtCat] p ON e.Id = p.ArtId 
WHERE p.CatId = @CategoryNum

在限制p.CatId = @CategoryNum

之后,您应该使用RowNum

猜测这是有效的:

SELECT [Id]
      ,[Title]
FROM (SELECT  [Id]
             ,[Title]
             ,ROW_NUMBER() OVER(ORDER BY id) as RowNum         
      FROM (SELECT [Id]
                  ,[Title]
            FROM Art
            ) as e
      INNER JOIN [ArtCat] p ON e.Id = p.ArtId 
      WHERE p.CatId = @CategoryNum
     )sub
WHERE RowNum BETWEEN @startIndex AND (@startIndex + @pageSize) 

答案 1 :(得分:0)

Goat CO你真的很有帮助!!谢谢。我们最终使用的代码是。

SELECT
       ROW_NUMBER() OVER(ORDER BY id) as e.RowNum  
       ,e.[Id]
      ,e.[Title]

FROM (SELECT  
          [Id]
         ,[Title]
         ,ROW_NUMBER() OVER(ORDER BY id) as RowNum         
  FROM 
     (SELECT
           ROW_NUMBER() OVER(ORDER BY id) as RowNum
           ,[Id]
           ,[Title]

           FROM Art
              INNER JOIN [ArtCat] p ON e.Id = p.ArtId 

       WHERE p.CatId = @CategoryNum
     ) as e
WHERE 
  e.RowNum BETWEEN @startIndex AND (@startIndex + @pageSize) 

预过滤结果(就像你有的那样),但要在外表上创建另一行来真正组织结果。

我的同事也抱怨我的格式太糟糕了。哈