Sql server 若子查询中的表与外部查询中的表具有相同的别名,会发生什么情况?

Sql server 若子查询中的表与外部查询中的表具有相同的别名,会发生什么情况?,sql-server,Sql Server,处理较大的查询以提高性能。我发现有一个spot具有子查询,但内部查询与外部查询具有相同的表,具有相同的别名。这是定义的行为吗 select * from documents d left join ( select distinct d.id, 'Yes' as 'IsCertainType' from documents d left join documentAttributes da on d.id = da.id where da.Description like '%Certa

处理较大的查询以提高性能。我发现有一个spot具有子查询,但内部查询与外部查询具有相同的表,具有相同的别名。这是定义的行为吗

select * from documents d
left join ( select distinct d.id, 'Yes' as 'IsCertainType' from documents d
    left join documentAttributes da on d.id = da.id where da.Description like '%CertainType%'
    ) #certainType
on d.Id = #certainType.Id

这很好,因为内部查询和外部查询具有不同的范围

这很好,因为内部查询和外部查询具有不同的范围

我认为根本没有理由使用子查询。只需执行
左连接
,就可以了

    select distinct d.id, 'Yes' as 'IsCertainType' 
    from documents d
    left join documentAttributes da 
    on d.id = da.id
    where da.Description like '%CertainType%'
或者,如我在注释中所述,如果表文档中具有相同id的其他行的值与按distinct返回的行的值不同,则可以执行
GROUP by

    select d.id, d.someColum, etc. 'Yes' as 'IsCertainType' 
    from documents d
    left join documentAttributes da 
    on d.id = da.id
    where da.Description like '%CertainType%'
    GROUP BY d.id, d.someColumn, etc..

我认为根本没有理由使用子查询。只需执行
左连接
,就可以了

    select distinct d.id, 'Yes' as 'IsCertainType' 
    from documents d
    left join documentAttributes da 
    on d.id = da.id
    where da.Description like '%CertainType%'
或者,如我在注释中所述,如果表文档中具有相同id的其他行的值与按distinct返回的行的值不同,则可以执行
GROUP by

    select d.id, d.someColum, etc. 'Yes' as 'IsCertainType' 
    from documents d
    left join documentAttributes da 
    on d.id = da.id
    where da.Description like '%CertainType%'
    GROUP BY d.id, d.someColumn, etc..

是的,我刚得出那个结论。实际的子查询有一大堆注释掉的东西,看起来这个子查询在某种程度上可能是必要的,但是在我消除了所有的混乱之后,我觉得“这只是一个d***左连接”@Kevin除非您需要表
文档
中的
id
以外的更多信息,就像在您的示例中,他们正在执行
SELECT*
,否则您始终可以修改我的答案以包括表
文档的其他列。
distinct
让我有点困扰,因为如果具有相同
id
的行的其他列具有不同的值,您可能会丢失所需的数据,如果是这种情况,我建议删除
distinct
并按
分组是的,我刚刚得出了这个结论。实际的子查询有一大堆注释掉的东西,看起来这个子查询在某种程度上可能是必要的,但是在我消除了所有的混乱之后,我觉得“这只是一个d***左连接”@Kevin除非您需要表
文档
中的
id
以外的更多信息,就像在您的示例中,他们正在执行
SELECT*
,否则您始终可以修改我的答案以包括表
文档的其他列。
distinct
有点困扰我,因为如果具有相同
id
的行的其他列具有不同的值,您可能会丢失所需的数据,如果是这种情况,我建议删除
distinct
并按
分组