'.' 附近的语法不正确在使用 Coalesce 时

Incorrect syntax near '.' while using Coalesce

我正在尝试连接三个表,我成功连接了两个。

这有效(两个 Tables)

SELECT  ImportExportBadFile.ID, ImportExportSettingID,
    ImportExportBadFile.UserID,
    Coalesce(UserName,'') UserName  
    FROM
    ImportExportBadFile 
    LEFT OUTER JOIN Users HGSQLUsers ON ImportExportBadFile.UserID = HGSQLUsers.ID
    ORDER BY  ImportExportBadFile.DateTimeStamp DESC

现在,当我尝试添加另一个 Table:

SELECT  ImportExportBadFile.ID, ImportExportSettingID,
    SETT.Name,
    ImportExportBadFile.UserID,
    Coalesce(UserName,'') HGSQLUsers.UserName  
    FROM
    ImportExportBadFile 
    LEFT OUTER JOIN Users HGSQLUsers ON ImportExportBadFile.UserID = HGSQLUsers.ID
    INNER JOIN ImportExportSettings SETT ON ImportExportBadFile.ImportExportSettingID = SETT.ID  
    ORDER BY  ImportExportBadFile.DateTimeStamp DESC

It gives Error : "Incorrect syntax near '.'." at line : "Coalesce(UserName,'') HGSQLUsers.UserName"

如果我只写 UserName 它给出

"Ambiguous column name 'UserName'."

求助。

可能 UserName 列存在于两个 table 中,您需要指定 table 想要从中获取 UserName,如下所示

SELECT  ImportExportBadFile.ID, ImportExportSettingID,
    SETT.Name,
    ImportExportBadFile.UserID,
    Coalesce( HGSQLUsers.UserName  ,'') as "HGSQLUsers.UserName"
    FROM
    ImportExportBadFile 
    LEFT OUTER JOIN Users HGSQLUsers ON ImportExportBadFile.UserID = HGSQLUsers.ID
    INNER JOIN ImportExportSettings SETT ON ImportExportBadFile.ImportExportSettingID = SETT.ID
ORDER BY  ImportExportBadFile.DateTimeStamp DESC

错误 "Incorrect syntax near '.'." at line : 来自别名 HGSQLUsers.UserName 您可以使用它,但要有配额。

我还建议您为每个 table 使用别名,如下所示 - 对我来说更具可读性

SELECT  I.ID, I.ImportExportSettingID,
        SETT.Name,
        I.UserID,
       Coalesce( HGSQLUsers .UserName  ,'') as "HGSQLUsers.UserName"
FROM ImportExportBadFile I
LEFT OUTER JOIN Users HGSQLUsers ON I.UserID = HGSQLUsers.ID
INNER JOIN ImportExportSettings SETT ON I.ImportExportSettingID = SETT.ID  
ORDER BY  I.DateTimeStamp DESC

实际上这对我来说在反复试验中很有效:

SELECT  ImportExportBadFile.ID, ImportExportSettingID,
    SETT.Name,
    ImportExportBadFile.UserID,
    Coalesce(HGSQLUsers.UserName,'')
    FROM
    ImportExportBadFile 
    INNER JOIN ImportExportSettings SETT ON ImportExportBadFile.ImportExportSettingID = SETT.ID  
    LEFT OUTER JOIN Users HGSQLUsers ON ImportExportBadFile.UserID = HGSQLUsers.ID
    ORDER BY  ImportExportBadFile.DateTimeStamp DESC

但@Parado 的回答更具体和解释。

谢谢。