对Union和Left Join的SQL查询

时间:2018-02-27 12:29:06

标签: sql-server union

我有这个查询

SELECT 
    fc.ID AS FileCategoryId
    ,fc.FolderCategoryName as FileCategoryName
    ,fcparent.ID AS FileParentCategoryID
    ,fcparent.FolderCategoryName AS FileParentName
    ,FileAllowView = 0
    ,FileAllowDownload = 0
    ,FileCategoryType = 0
FROM 
    FolderCategory AS fc 
    LEFT JOIN FolderCategory AS fcparent ON fc.FolderParentCategoryId = fcparent.ID

UNION

SELECT 
    f.ID as FileCategoryId 
    ,f.FileName as FileCategoryName
    ,f.FolderCategoryId as FileParentCategoryId
    ,ffcparent.FolderCategoryName AS FileParentName
    ,FileAllowView = (Case when fp.AllowView IS Null Then 1 ELSE fp.AllowView END)
    ,FileAllowDownload = (Case when fp.AllowDownload IS Null Then 1 ELSE fp.AllowDownload END)
    ,FileCategoryType = 1
FROM 
    [dbo].Files as f
    LEFT JOIN [dbo].FolderCategory as ffcparent ON f.FolderCategoryId = ffcparent.ID
    LEFT JOIN FilePermissions as fp ON  f.ID = fp.FileId
Where FileAllowView = 1

但它给了我无效的列名“FileAllowView”,但我将其声明为列。请帮帮我。

2 个答案:

答案 0 :(得分:0)

更新WHERE条件,如下所示,在当前条件下,您应用了范围内不存在的列(FileAllowView)上的逻辑。相反,您可以将新列应用于初始列fp.AllowView

的条件

我已转换为BIT,如果为INTEGER值,则将其转换为INT

Where CAST(ISNULL(fp.AllowView,1) AS BIT) = 1

OR

Where (fp.AllowView=1 OR fp.AllowView IS NULL)

答案 1 :(得分:0)

根据SQL中的逻辑过程,首先执行WHERE子句,然后执行SELECT子句,但是您在SELECT子句中提到了新列,这是SQL Server在尝试执行WHERE时抛出错误的原因表中包含未知列的子句,尝试根据您的条件修改WHERE子句,但不要使用别名来修改。