SQL Server与JOIN的分页 - 不明确的列名'id'

时间:2016-05-31 06:54:07

标签: sql-server join pagination

我无法修复一个通常在没有JOIN的情况下使用的查询,但是现在我想加入几个表,我看到一个错误的列名称ID不明确。

  

SQLSTATE [42000]:[Microsoft] [SQL Server Native Client 11.0] [SQL Server]不明确的列名'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

如果我只尝试JOIN进入Management SQL studio,代码JOIN成功完成。所以我认为麻烦id在这里是ORDER BY id子句。

有没有办法在此查询中使用JOIN? 谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您的DriverCompanyPositions表格都有id列,名称id不明确。您应该在order by条款中完全符合条件。 E.g:

ORDER BY t.id