2011-03-09 162 views
1

我使用這個查詢分頁SQL Server的連接查詢問題

SELECT * 
FROM 
    (SELECT ROW_NUMBER() OVER (ORDER BY {0} {1}) AS RowNum, * 
    FROM Cars 
    WHERE IdOwner = {2}) AS Rows 
WHERE RowNum > {3} AND RowNum < {4} 

我想使分頁查詢2個表,而不是隻有一個,因爲我現在要做的。

SELECT * 
FROM 
    (SELECT ROW_NUMBER() OVER (ORDER BY {0} {1}) AS RowNum, 
      Cars.Id, Cars.Make, Cars.Model, Color.Name 
    FROM Cars 
    INNER JOIN Color ON Cars.ColorId = Color.Id 
    WHERE IdOwner = {2}) AS Rows 
WHERE RowNum > {3} AND RowNum < {4} 

我得到一個Incorrect syntax near the keyword 'WHERE'.

問題解決了。謝謝你們,我這種小白:(

SELECT * 
FROM (SELECT ROW_NUMBER() OVER (ORDER BY c.Id ) AS RowNum, 
     c.Id, c.Make, c.Model, d.ColorName 
     FROM Car AS c 
     INNER JOIN Color AS d 
     ON c.ColorId = d.Id WHERE c.IdOwner=1) AS Rows 
WHERE RowNum > 0 AND RowNum < 11 
+1

什麼的'{0}''.. {4}'?你應該使用參數化的值無論如何不是字符串串聯 – 2011-03-09 15:29:15

+0

好吧, s沒有直接解決你的問題,但你通常應該在你的程序中分頁,而不是在數據庫中分頁。將相關信息加載到數組中,然後進行分頁。 – syrion 2011-03-09 15:30:58

+3

@syrion:如果你有數百萬行,你**不會**想把所有的東西都拉回到客戶端,然後分頁...... – 2011-03-09 15:31:48

回答

1

c.Make多次指定和 「爲行」 已被刪除,是必要的。

SELECT * 
FROM (SELECT ROW_NUMBER() OVER (ORDER BY c.Id ) AS RowNum, 
     c.Id, c.Make, c.Model, d.ColorName 
     FROM Car AS c 
     INNER JOIN Color AS d 
     ON c.ColorId = d.Id WHERE c.IdOwner=1) AS Rows 
WHERE RowNum > 0 AND RowNum < 11 
4

這可能是一個問題的支架,你必須前綴您IdOwner小心你的前綴{0}和{1}參數:

SELECT ROW_NUMBER() OVER (ORDER BY {0} {1}) AS RowNum, 
     Cars.Id,Cars.Make, Cars.Model, Color.Name 
FROM (Cars INNER JOIN Color ON Cars.ColorId=Color.Id) 
WHERE Cars.IdOwner={2} 
+0

從我所知道的看來,{1}看起來就像是一個排序方向。我不確定添加的括號會對幫助(或傷害)產生什麼影響。不過,您絕對正確地確保列的前綴/限定。正確的。 – Enull 2011-03-09 16:31:55

+0

那麼你是對的,括號可能不會在SQL Server中變得好或錯。我與Access混淆的是,如果支架可以省略,它可以造成很大的傷害。 – 2011-03-09 16:37:15