2016-05-31 78 views
1

我無法修復一個通常沒有JOIN使用的查詢,但現在我想加入幾個表,並且我看到一個模糊的列名稱id錯誤。加入SQL Server分頁 - 不明確的列名'id'

SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Ambiguous column name 'id'.1

這是我使用的代碼:

SELECT * FROM 
      (SELECT ROW_NUMBER() OVER(ORDER BY id desc) 
      AS RowNumber, 
      d.id as iddr, d.EGN, d.Names, d.NickName, d.Residence, d.PersonalMobilePhone, d.HomeAddress,d.GarantPerson, d.InsertDate, 
      t.id, t.PossitionName, 
      de.id, de.IdDriver, de.IdPAFirms,de.IdPossition 
      FROM dbo.Driver d 
      FULL JOIN dbo.DriversEmployed de ON d.id = de.IdDriver 
      FULL JOIN dbo.CompanyPossitions t ON de.IdPossition = t.id) 
     AS TEST 
     WHERE RowNumber BETWEEN ? AND ? + 1 

,如果我嘗試只能加入到管理SQL工作室的代碼JOIN succesfull。所以我想這個問題id在這裏是ORDER BY id子句。

有沒有辦法在這個查詢中使用JOIN? 謝謝!

+0

您需要在'ROW_NUMBER()OVER(ORDER BY ID DESC)'中爲'id'加適當的表別名。 –

回答

1

在你ROW_NUMBER功能:

ROW_NUMBER() OVER (ORDER BY id DESC) AS RowNumber 

你需要以指示使用適當的表的別名前綴從該表中的列id是從,即

ROW_NUMBER() OVER (ORDER BY d.id DESC) AS RowNumber 

此外,您需要將不同的列別名分配給類似的列:

SELECT * 
FROM (
    SELECT 
     ROW_NUMBER() OVER (ORDER BY d.id DESC) AS RowNumber, 
     d.id AS iddr, -- Here 
     d.EGN, 
     d.Names, 
     d.NickName, 
     d.Residence, 
     d.PersonalMobilePhone, 
     d.HomeAddress, 
     d.GarantPerson, 
     d.InsertDate, 
     t.id AS CompanyPossitionsId, -- Here 
     t.PossitionName, 
     de.id AS DriversEmployedId, -- Here 
     de.IdDriver, 
     de.IdPAFirms, 
     de.IdPossition 
    FROM dbo.Driver d 
    FULL JOIN dbo.DriversEmployed de 
     ON d.id = de.IdDriver 
    FULL JOIN dbo.CompanyPossitions t 
     ON de.IdPossition = t.id 
) AS TEST 
WHERE 
    RowNumber BETWEEN ? AND ? + 1 
+0

謝謝,我嘗試這個,但其他錯誤:SQLSTATE [42000]:[微軟] [SQL Server本機客戶端11.0] [SQL服務器]'列'id''多次指定爲'TEST'.1 – Nasko

+0

@Hacko,請參閱我的更新的答案。 –

+1

謝謝,現在我明白了。 – Nasko

0

您的DriverCompanyPositions表都有一個id列,使得名稱id含糊不清。你應該完全符合你的條款order by條款。例如:

ORDER BY t.id 
+0

謝謝你,我嘗試了這個,但其他錯誤:SQLSTATE [42000]:[微軟] [SQL Server Native Client 11.0] [SQL Server]'TEST'多次指定'id'列.1 – Nasko