具有分页和排序的SQL语句

时间:2017-11-18 14:50:01

标签: sql-server pagination

我有两张桌子 UserProfile &具有 ManyToMany 关系的 UserConnections 。 表 UserConnections 有两个字段" uniqueProfileID " &安培; " connectionProfileID ",这两个字段都是表 UserProfile 中相同字段的外键,即" uniqueProfileID &#34 ;. 就像表 UserConnections 一样,一个 uniqueProfileID 可以有多个 connectionProfileID

我需要从表 UserProfile 中检索 uniqueProfileID ProfileName ,其中 connectionProfileID 不在 uniqueProfileID中 UserConnections ,我还需要在查询中实现分页。

我已经编写了这样的查询,但是我收到了错误" 多部分标识符" UP.ProfileName"无法受约束。"

SELECT * FROM  
      ( 
      SELECT RoRowConstrainedResult2.* ,  ROW_NUMBER() OVER ( ORDER BY UP.ProfileName ASC) RowNum
      FROM      
      (
      SELECT UP.uniqueProfileID,UP.ProfileName,ROW_NUMBER() OVER (ORDER BY UP.ProfileName ASC) RowNum2
      FROM dbo.UserProfile UP LEFT JOIN
      dbo.UserConnections UC ON UC.connectionProfileID = UP.uniqueProfileID
      WHERE ProfileName LIKE ('abhi' + '%') AND UP.uniqueProfileID NOT IN 
      (select Distinct(connectionProfileID) from dbo.UserConnections WHERE uniqueProfileID = 42) AND UP.uniqueProfileID !=42) RoRowConstrainedResult2
      )  RowConstrainedResult       

  WHERE    RowNum >= 1 AND RowNum <= 2

我在ORDER BY的第3行收到错误 UP.ProfileName

我试着解决这个问题超过一天,但我不能。

1 个答案:

答案 0 :(得分:0)

别名UP来自子查询内部,您为最内部子查询的结果提供的别名是RoRowConstrainedResult2。只需更改第三行,如下所示。

   SELECT * FROM  
          ( 
          SELECT RoRowConstrainedResult2.* ,  ROW_NUMBER() OVER ( ORDER BY RoRowConstrainedResult2.ProfileName ASC) RowNum
          FROM      
          (
          SELECT UP.uniqueProfileID,UP.ProfileName,ROW_NUMBER() OVER (ORDER BY UP.ProfileName ASC) RowNum2
          FROM dbo.UserProfile UP LEFT JOIN
          dbo.UserConnections UC ON UC.connectionProfileID = UP.uniqueProfileID
          WHERE ProfileName LIKE ('abhi' + '%') AND UP.uniqueProfileID NOT IN 
          (select Distinct(connectionProfileID) from dbo.UserConnections WHERE uniqueProfileID = 42) AND UP.uniqueProfileID !=42) RoRowConstrainedResult2
          )  RowConstrainedResult       

      WHERE    RowNum >= 1 AND RowNum <= 2