【发布时间】:2017-03-23 16:05:13
【问题描述】:
对于以下两个查询,我得到了不同的结果,我不知道为什么。唯一的区别是一个有一个IN,一个有一个equals。
在我进入查询之前,您应该知道我找到了一个更好的方法,将子查询移动到一个公共表表达式中,但这仍然让我发疯!我真的很想知道是什么导致了这个问题,我是出于好奇而问的
这是第一个查询:
use [DB.90_39733]
Select distinct x.uniqproducer, cn.Firstname,cn.lastname,e.code,
ecn.FirstName, ecn.LastName, ecn.entid, x.uniqline
from product x
join employ e on e.EmpID=x.uniqproducer
join contactname cn on cn.uniqentity=e.uniqentity
join [ETL_GAWR92]..idlookupentity ide on ide.enttype='EM'
and ide.UniqEntity=e.UniqEntity
left join [ETL_GAWR92]..EntConName ecn on ecn.entid=ide.empid
and ecn.opt='Y'
Where x.UniqProducer =(SELECT TOP 1 idl.UniqEntity
FROM [ETL_GAWR92]..IDLookupEntity idl
LEFT JOIN [ETL_GAWR92]..Employ e2 ON e2.ProdID = ''
WHERE idl.empID = e2.EmpID AND
idl.EntType = 'EM')
第二个:
use [DB.90_39733]
Select distinct x.uniqproducer, cn.Firstname,cn.lastname,e.code,
ecn.FirstName, ecn.LastName, ecn.entid, x.uniqline
from product x
join employ e on e.EmpID=x.uniqproducer
join contactname cn on cn.uniqentity=e.uniqentity
join [ETL_GAWR92]..idlookupentity ide on ide.enttype='EM'
and ide.UniqEntity=e.UniqEntity
left join [ETL_GAWR92]..EntConName ecn on ecn.entid=ide.empid
and ecn.opt='Y'
Where x.UniqProducer IN (SELECT TOP 1 idl.UniqEntity
FROM [ETL_GAWR92]..IDLookupEntity idl
LEFT JOIN [ETL_GAWR92]..Employ e2 ON e2.ProdID = ''
WHERE idl.empID = e2.EmpID AND
idl.EntType = 'EM')
第一个查询返回 0 行,而第二个查询返回 2 行。唯一的区别是最后一个 where 子句的 x.UniqProducer = 与 x.UniqProducer IN。
感谢您的宝贵时间
【问题讨论】:
-
可能是因为
SELECT TOP 1不保证每次都返回相同的记录。ORDER BY应该会有所帮助。 -
感谢瑞克,成功了。我很困惑,因为单独运行子查询总是返回相同的结果
标签: sql sql-server