分页和内部联接

时间:2012-04-17 09:33:29

标签: sql-server tsql sql-server-2008-r2 inner-join

我有一种情况需要与INNET JOIN一起进行分页。这是我的类似场景:

DECLARE @categories AS TABLE(
    CatID INT,
    CategoryName NVARCHAR(100)
);

DECLARE @fooTable AS TABLE(
    ID INT,
    CatID INT,
    Name NVARCHAR(100),
    MinAllow INT,
    Price DECIMAL(18,2)
);

INSERT INTO @categories  VALUES(1, 'Cat1');
INSERT INTO @categories  VALUES(2, 'Cat2');
INSERT INTO @categories  VALUES(3, 'Cat3');
INSERT INTO @categories  VALUES(4, 'Cat4');
INSERT INTO @categories  VALUES(5, 'Cat5');

INSERT INTO @fooTable  VALUES(1, 1, 'Product1', 2, 112.2);
INSERT INTO @fooTable  VALUES(3, 1, 'Product3', 5, 233.32);
INSERT INTO @fooTable  VALUES(6, 1, 'Product6', 4, 12.43);
INSERT INTO @fooTable  VALUES(7, 4, 'Product7', 4, 12.43);
INSERT INTO @fooTable  VALUES(8, 5, 'Product8', 4, 12.43);

这些是我的记录。如您所见,某些类别在@fooTable内没有任何产品。下一步,我们有以下SELECT声明:

SELECT * FROM @fooTable ft
INNER JOIN (
    SELECT ROW_NUMBER() OVER (ORDER BY CatID) AS RowNum, * FROM @categories
) AS cat ON (cat.CatID = ft.CatID);

这是一个基本的JOIN,除了输出还将携带类别的行号。我得到的查询结果如下:

ID   CatID   Name          MinAllow    Price     RowNum   CatID    CategoryName
---- ------- ------------- ----------- --------- -------- -------- -------------
1    1       Product1      2           112.20    1        1        Cat1
3    1       Product3      5           233.32    1        1        Cat1
6    1       Product6      4           12.43     1        1        Cat1
7    4       Product7      4           12.43     4        4        Cat4
8    5       Product8      4           12.43     5        5        Cat5

当您查看RowNum列时,您会看到这些值不是分页友好的。所以,当我尝试按如下方式对该表进行分页时,输出结果不正确:

SELECT * FROM @fooTable ft
INNER JOIN (
    SELECT ROW_NUMBER() OVER (ORDER BY CatID) AS RowNum, * FROM @categories
)AS cat ON (cat.CatID = ft.CatID) AND (cat.RowNum BETWEEN 1 AND 2);

我的实际情况与此类似,但该查询非常复杂,我需要使用INNER JOIN。我希望我说清楚。知道我是怎么做到的吗?

修改

根据我的第一个选择查询的上述结果,我应该能够在第二个查询中检索CatID为1和4的产品。这就是我的目标。

1 个答案:

答案 0 :(得分:7)

一个解决方案可以是下一个解决方案:

SELECT  x.*
FROM
(
        SELECT  ft.*, 
                cat.CategoryName,
                DENSE_RANK() OVER (ORDER BY ft.CatID) AS Rnk
        FROM @fooTable ft
        INNER JOIN @categories cat ON (cat.CatID = ft.CatID)
) AS x
WHERE   x.Rnk BETWEEN 1 AND 2

结果:

ID CatID Name     MinAllow Price   CategoryName Rnk
-- ----- -------- -------- ------- ------------ ---
1  1     Product1 2        112.20  Cat1         1
3  1     Product3 5        233.32  Cat1         1
6  1     Product6 4        12.43   Cat1         1
7  4     Product7 4        12.43   Cat4         2