2013-04-01 73 views
0

我有兩個表 - Item和Order。SQL內部連接分頁

Item 
===================== 
ID, ItemName 


Order 
======================== 
orderID, ID , status 

我想通過使用內加入表連接:

SELECT Order.orderID, Order.ID, Item.ItemName 
FROM Order 
INNER JOIN Item 
ON Order.ID=Item.ID 

但問題我需要做的PHP分頁。

我有代碼,但我不知道如何修改它,因爲我的SQL不是很好。

下面是代碼(我已經修改並能與「*」顯示,但不知道如何運用如上內加入下面的代碼):

SELECT TOP 20 * FROM 
(
SELECT ROW_NUMBER() OVER (ORDER BY Order.orderID) AS RowNumber, *, TotalRows=Count(*) OVER() 
FROM Order WHERE status=1 
) _tmpInlineView 
WHERE RowNumber >= 20 AND status=1 ORDER BY Order.orderID 

在此先感謝。

+0

? ?你應該命名它項目我猜 –

+0

糟糕,我編輯了內部連接。對不起,我的錯誤 – Genjo

回答

1

把你的連接順序見下表:

SELECT TOP 20 * FROM 
(
SELECT ROW_NUMBER() OVER (ORDER BY Order.orderID) AS RowNumber, Order.orderID, Order.ID, Item.ItemName, TotalRows=Count(*) OVER() 
FROM Order INNER JOIN Item 
ON Order.ID=Item.ID WHERE status=1 
) _tmpInlineView 
WHERE RowNumber >= 20 ORDER BY _tmpInlineView.orderID 
+0

這是我得到的: [SQL Server]不明確的列名'orderID'。 [message] => [Microsoft] [SQL Server Native Client 10.0] [SQL Server]不明確的列名'orderID'。 )[1] =>數組([0] => 42000 [SQLSTATE] => 42000 [1] => 8156 [code] => 8156 [2] => [Microsoft] [SQL Server Native Client 10.0] ]對'_tmpInlineView'多次指定了'orderID'列。[message] => [Microsoft] [SQL Server Native Client 10.0] [SQL Server]對'_tmpInlineView'多次指定了'orderID'列。) – Genjo

+0

檢查更新後的答案 –

+0

太棒了!非常感謝 ! – Genjo

1

在你的內部聯接查詢,其中就個人表來使用試試這個

 SELECT TOP 20 * FROM 
     (
     SELECT ROW_NUMBER() OVER (ORDER BY Order.orderID) AS RowNumber, ORDER.*, 
Count(1) OVER() as TotalRows 
     FROM ORDER INNER JOIN Item ON Order.ID=Item.ID 
     WHERE status=1 
     ) _tmpInlineView 
     WHERE RowNumber >= 20 ORDER BY orderID 

或嘗試這個

SELECT * 
    FROM ORDER INNER JOIN Item ON Order.ID=Item.ID WHERE status=1 
    ORDER BY Order.orderID 
    OFFSET (@PageNo - 1) * @RecordsPerPage ROWS 
    FETCH NEXT @RecordsPerPage ROWS ONLY 

The following are the limitations of using Offset Fetch: 
1) Fetch Next can't be used standalone, it requires Offset 
2) Offset can't be used standalone, it requires order by 
3) Top can't be combined with offset fetch next in the same query expression 
+0

嗨, 我試過,我得到這個錯誤:無效的列名「狀態」 ,當我嘗試改變狀態Order.status 我得到:多部分組成的標識符「Order.status」無法綁定 – Genjo

+0

查看已更新回答 – Harshil

+0

感謝您的回答 – Genjo