SQL子查询范围

时间:2017-09-29 13:31:20

标签: sql tsql scope

请考虑这段代码:

exists 
                        (
                            select 1 from dt dt1 inner join pt pt1 on dt1.map=pt1.map and dt1.pda=pt1.pda where c.code=dt1.customer and dt1.canceled=0 and dt1.doccode in ('02','03') and pt1.exp_value<>0
                                and dt1.insdate>='20151001'
                                and pt1.item in (select item from f_itemset where itemset='campaign78' and cat_custom='complexion_sccf')
                        )
                        and not exists
                        (
                            select 1 from dt dt2 inner join pt pt2 on dt2.map=pt2.map and dt2.pda=pt2.pda where c.code=dt2.customer and dt2.canceled=0 and dt2.doccode in ('02','03') and pt2.exp_value<>0 
                                and dt2.insdate>='20151001'
                                and pt2.item not in (select item from f_itemset where itemset='campaign78' and cat_custom='complexion_sccf')
                        )

请注意,这是一个查询,在where部分,我还应该提到表pt,dt也出现在from子句中。问题是:所有这些别名(dt1,dt2等)是否必要?如果我不给他们这些别名,我是否会因为担心他们可能与外部查询相关/ pt相关而变得过于偏执?

1 个答案:

答案 0 :(得分:0)

看看完美运行的这个(愚蠢的)查询:

SELECT * FROM TAGS AS T
WHERE T.[COUNT]< 10
AND T.ID IN (SELECT O.ID FROM TAGS AS O WHERE O.[COUNT]=9 OR O.ID = T.ID)

您可以看到子查询使用第一个数据......

Normaly,SQL Server会警告你,如果它可以确定使用的女巫表,强迫你设置别名......但请记住,你应该总是设置别名。

因此,您必须在查询中保留别名pt1和pt2。