PHP MS_SQL分页错误与查询

时间:2012-11-29 10:40:06

标签: php sql-server pagination

我是PHP的新手,甚至更新的PHP使用MS SQL,而不是MySQL。在做了一些研究之后,我想出了一个可以被视为分页查询的东西,但显然我在某个地方出错了,因为它会抛出一个错误。我不明白为什么。

下面是查询:

SELECT TOP 10 * FROM Products WHERE SubCatID = '".$scid."' and ProductID NOT IN ( SELECT TOP 0 * FROM Products ORDER BY ProductID ASC ) ORDER BY ProductID ASC

继承错误:

Warning: mssql_query() [function.mssql-query]: message: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. (severity 16)

我理解这是因为子查询,但任何人都可以指出我正确的方向吗?

2 个答案:

答案 0 :(得分:2)

您必须在子查询中只选择一列。实施例

SELECT TOP 10 * FROM Products WHERE SubCatID = '".$scid."' and ProductID NOT IN ( SELECT TOP 0 ProductID FROM Products ORDER BY ProductID ASC ) ORDER BY ProductID ASC

答案 1 :(得分:0)

使用更好的分页查询是这样的:

SELECT * FROM (
  SELECT Products.*, 
         ROW_NUMBER() OVER (ORDER BY ProductID) AS __RN
    FROM Products WHERE SubCatID = '".$scid."' ORDER BY ProductID
) numberedRows
WHERE __RN BETWEEN 1 and 10

然后,您可以将最后一行的数字替换为您想要的行号。通常,你不应该使用*。实际上,您将在结果集上获得一个名为__RN的额外列。如果指定列名,则不会发生这种情况。