如何弄清楚语法错误?

时间:2013-12-20 16:11:29

标签: sql sql-server

我正在尝试编写一个不断给我语法错误的SQL查询。问题是,错误信息根本没有帮助我。

以下是查询:

SELECT * 
FROM
   (SELECT     
        dbo.ciqCompanyUltimateParent.ultimateParentCompanyId, 
        COUNT(DISTINCT dbo.ciqCompany.companyId) AS Subsidiaries_Count, 
        COUNT(DISTINCT dbo.ciqCountryGeo.countryId) AS Countries_Count
    FROM         
        dbo.ciqCompanyUltimateParent 
    INNER JOIN
        dbo.ciqCompany ON dbo.ciqCompanyUltimateParent.companyId = dbo.ciqCompany.companyId  
    INNER JOIN
        dbo.ciqCountryGeo ON dbo.ciqCompany.countryId = dbo.ciqCountryGeo.countryId
    GROUP BY 
        dbo.ciqCompanyUltimateParent.ultimateParentCompanyId
     )
INNER JOIN 
    dbo.ciqCompany ON ultimateParentCompanyId = dbo.ciqCompany.companyId 

括号中的东西在我执行它时工作正常(即它执行并返回一个表)。但是,最后一个INNER JOIN给出了以下错误:

  

Msg 156,Level 15,State 1,Line 10
  关键字“INNER”附近的语法不正确。

更糟糕的是,当我将上述陈述减少到

SELECT * 
FROM
    (SELECT     
        dbo.ciqCompanyUltimateParent.ultimateParentCompanyId, 
        COUNT(DISTINCT dbo.ciqCompany.companyId) AS Subsidiaries_Count, 
        COUNT(DISTINCT dbo.ciqCountryGeo.countryId) AS Countries_Count
     FROM         
        dbo.ciqCompanyUltimateParent 
     INNER JOIN
        dbo.ciqCompany ON dbo.ciqCompanyUltimateParent.companyId = dbo.ciqCompany.companyId 
     INNER JOIN
        dbo.ciqCountryGeo ON dbo.ciqCompany.countryId = dbo.ciqCountryGeo.countryId
     GROUP BY 
        dbo.ciqCompanyUltimateParent.ultimateParentCompanyId
    )

我得到了类似的错误 -

  

Msg 102,Level 15,State 1,Line 9
  ')'附近的语法不正确。

为什么我不能从正常工作的查询中选择*?

2 个答案:

答案 0 :(得分:6)

尝试对子查询进行别名处理。 E.g。

SELECT * FROM
(
 ....
) SUB
INNER JOIN dbo.ciqCompany 
ON SUB.ultimateParentCompanyId = dbo.ciqCompany.companyId 

答案 1 :(得分:-4)

鉴于dbo,你在MS SQL Server上?您需要在括号中嵌入多个连接:

SELECT ..
FROM table1
JOIN (table2 ON ...
    JOIN (table3 ON ...
        JOIN table4 ON ...
            etc...
    )
)