0

这是我的查询。当我内部加入 2 个表时,没有问题。

 SELECT S.* ,
        U.Avatar ,
        U.Displayname ,
        ROW_NUMBER() OVER ( ORDER BY S.Id DESC ) rownum
 FROM   dbo.Smoothie AS S
        INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
 WHERE  S.IsPublic = 1
        AND S.Status = 3
        AND S.UserId = 2

然后,我添加了另一个内部连接。现在,我得到了很多重复。

SELECT  S.* ,
        U.Avatar ,
        U.Displayname,
        ROW_NUMBER() OVER ( ORDER BY S.Id DESC ) rownum
FROM    dbo.Smoothie AS S
        INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
        INNER JOIN dbo.Favorite AS F ON U.Id = F.UserId
WHERE   S.IsPublic = 1
        AND S.Status = 3
        AND F.UserId = 2

一种解决方案是使用 distinct。但是,我必须注释掉 row_number,我需要那个 row_number 来进行分页。有没有另一种方法来摆脱重复?

SELECT  DISTINCT S.* ,
        U.Avatar ,
        U.Displayname 
        -- ROW_NUMBER() OVER ( ORDER BY S.Id DESC ) rownum
FROM    dbo.Smoothie AS S
        INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
        INNER JOIN dbo.Favorite AS F ON U.Id = F.UserId
WHERE   S.IsPublic = 1
        AND S.Status = 3
        AND F.UserId = 2
4

2 回答 2

3

为什么不使用您拥有的查询,而不使用 row_number 作为子查询,然后稍后再添加行号:

SELECT *, 
    ROW_NUMBER() OVER ( ORDER BY subQuery.Id DESC ) rownum
FROM (
SELECT  DISTINCT S.* ,
    U.Avatar ,
    U.Displayname 
FROM    dbo.Smoothie AS S
    INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
    INNER JOIN dbo.Favorite AS F ON U.Id = F.UserId
WHERE   S.IsPublic = 1
    AND S.Status = 3
    AND F.UserId = 2
) AS subQuery
于 2013-01-03T01:25:55.267 回答
0

Dense_Rank也可以使用您原本未修改的查询来完成这项工作。

于 2013-01-03T07:01:59.140 回答