为什么这个“分页”查询会抛出“与表名或别名不匹配”错误?

时间:2011-08-30 04:57:42

标签: sql sql-server-2008 pagination

警告,“丑陋”查询警报(MS SQL Server 2008):

SELECT BaseDocs.* FROM (
  SELECT ROW_NUMBER() OVER (ORDER BY BaseDocs.DateUpdated DESC) AS Row, BaseDocs.* 
    FROM BaseDocs INNER JOIN DocCats ON BaseDocs.DocId = DocCats.DocId  
    WHERE DocCats.CatId IN (4) AND BaseDocs.BaseId = 1
  ) AS Paged 
  WHERE Row > 0 AND Row <=3

此查询引发此错误:

  

列前缀“BaseDocs”与表名或别名不匹配   查询中使用的名称。

此查询针对这些表:

BaseDocs Table
 - DocId PK
 - BaseId FK
 - ...

DocCategories Table
 - CatId PK
 - ...

DocCats (join) Table
 - DocId FK PK 
 - CatId FK PK

在对这个问题进行“黑客攻击”这么久之后,我认为我的大脑正在煎炸......但它很接近,我能感受到它。提前谢谢!

1 个答案:

答案 0 :(得分:3)

只是不要在SELECT中指定一个表别名 - 该表别名仅在您的子查询 中可见!

SELECT *
FROM 
   (SELECT 
        ROW_NUMBER() OVER (ORDER BY BaseDocs.DateUpdated DESC) AS Row, 
        BaseDocs.* 
    FROM BaseDocs 
    INNER JOIN DocCats ON BaseDocs.DocId = DocCats.DocId  
    WHERE 
         DocCats.CatId IN (4) 
         AND BaseDocs.BaseId = 1
  ) AS Paged 
WHERE 
   Row > 0 AND Row <= 3

或者:使用给定子查询的别名:

SELECT Paged.* .....