SQL:select中的简单自定义列不起作用?

时间:2015-12-26 13:41:24

标签: sql sql-server sql-server-2008 tsql laravel

如果我在select中添加自定义列,则会出现此错误:

  

20018无效的列名称为“2”。

这是查询示例

SELECT
    [msg].[MessageTo],
    [msg].[MessageFrom],
    [msg].[SendTime],
    [msg].[ReceiveTime],
    [msg].[id],
    '2' AS source,
    [kat].[id] AS [CategoriId],
    [kat].[naziv] AS [CategoriName]
FROM
    [SMSServer_1].[dbo].[MessageIn] AS [msg]
LEFT JOIN [Tekijanka].[dbo].[crm_poruka] AS [por] ON [por].[fk_poruka] = [msg].[id]
AND [por].[fk_source] = [2]
LEFT JOIN [Tekijanka].[dbo].[crm_kategorije_poruka] AS [kat] ON [kat].[id] = [por].[fk_kategorija]
WHERE
    msg.id NOT IN (
        SELECT
            fk_poruka
        FROM
            Tekijanka.dbo.crm_poruka
        WHERE
            fk_status <> 1
    )
ORDER BY
    [SendTime] DESC

有没有办法解决它?

1 个答案:

答案 0 :(得分:2)

问题出在LEFT JOIN,而不在SELECT部分:

AND [por].[fk_source] = [2]

此条件尝试加入fk_source和列名为 [2]。当然,表MessageIncrm_poruka中没有这样的列。您必须更改此部分代码(删除条件或将其更改为AND [por].[fk_source] = 2)。