【问题标题】:SQL Server 2008 R2 paginationSQL Server 2008 R2 分页
【发布时间】:2011-06-19 18:46:15
【问题描述】:

我需要为我的联合查询实现分页,但我收到错误消息“Msg 102, Level 15, State 1, Line 14 ')' 附近的语法不正确。”。我按照从 link 中找到的示例进行操作。

select * 
  from (select Id, 
               row_number() OVER (order by Id asc) as RowNumber 
          from (select Id 
                  from (select Id 
                          from Table1) as table1 
                union all 
                select Id 
                  from (select Id 
                          from Table2) as table2)) as t Derived 
  WHERE RowNumber > 5 
    and RowNumber <= 10

【问题讨论】:

  • 发生了什么?你有错误吗?
  • 更新了答案以包含错误消息。
  • 我从不喜欢 SQL Server 的错误位置,但我在你的代码中数了 12 行。有什么没贴的吗?
  • 我刚刚删除了真实的列名,所以它可能比真实的查询短。

标签: sql sql-server tsql sql-server-2008 pagination


【解决方案1】:

用途:

SELECT u.* 
  FROM (SELECT t.id, 
               ROW_NUMBER() OVER (ORDER BY t.id) as rownum 
          FROM (SELECT t1.id 
                  FROM TABLE1 t1
                UNION ALL 
                SELECT t2.id 
                  FROM TABLE2 t2) as t) AS u
 WHERE u.rownum > 5 
   AND u.rownum <= 10

在我看来,您的查询缺少名为“派生”的派生表的右括号,但 UNION 中不需要子查询,因此我已将其删除。

【讨论】:

  • 似乎不是缺少括号,而是缺少表别名(对于 UNION ALL 子选择)。不管怎样,你已经把它重组得更好了。
  • 我喜欢。我用于分页的一个轻微推导是:`SELECT TOP(5) u.* FROM (SELECT t.id, ROW_NUMBER() OVER (ORDER BY t.id) as rownum FROM (SELECT t1.id FROM TABLE1 t1 UNION ALL SELECT t2.id FROM TABLE2 t2) as t) AS u WHERE u.rownum > 5'
【解决方案2】:

如果您从子查询中选择,那么您必须为其提供别名。您有 2 个外部子查询,但只有一个具有别名。应该是:from Table2) as tabl2) as t) as t

【讨论】:

    【解决方案3】:

    你只需要移动一个括号:

    from Table2) as table2)) as t Derived 应为 from Table2) as table2) as t) Derived

    您还可以删除一些使 Table1 成为 table1 和 Table2 成为 table2 的子查询,但我认为那里的那些子查询还有其他原因(比如这是基于另一个更复杂的查询)

    【讨论】:

    • 不,它并没有更复杂,而且它在你的建议下工作得很好,thanx!
    【解决方案4】:
    select * 
      from (select Id, 
                   row_number() OVER (order by Id asc) as RowNumber 
              from (select Id 
                      from Table1 as table1 
                    union all 
                    select Id 
                      from Table2)p)t 
      WHERE RowNumber > 5 
        and RowNumber <= 10
    

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 2013-02-07
      • 2012-10-05
      相关资源
      最近更新 更多