SQL SELECT语句日期时间与内部联接的麻烦

时间:2016-03-03 15:37:03

标签: sql sql-server datetime

我有这个查询没有返回任何记录,因为它与查询中的内连接时指定的grp.EffectiveDate不匹配。数据库是SQL Server。

SELECT grp.GroupID, grp.GroupNumber, grp.Name, grp.Location, grp.GroupTypeID, grp.DivisionID, 
grp.MasterGroupID, grp.EffectiveDate, grp.TerminationDate, crt.[ContractNumber], pln.[PBPNumber], div.SiteName, src.Name as SourceName 
FROM [Group] grp 
    INNER JOIN [IndividualPlanDemographic] idp ON grp.GroupID = idp.IndividualPlanDemographicID 
    INNER JOIN [Plan] pln ON idp.PlanID = pln.PlanID 
    INNER JOIN [Contract] crt ON pln.ContractID = crt.ContractID 
    INNER JOIN [Division] div ON grp.DivisionID = div.DivisionID 
    INNER JOIN [SourceSystem] src ON div.SourceSystemID = src.SourceSystemID 
WHERE 1 = 1 
AND grp.EffectiveDate = '1/1/2015 12:00:00 AM' AND grp.GroupTypeID = '2' ORDER BY ContractNumber

但是,如果我只查询主“组”表,它将根据所有条件返回我正在寻找的正确记录。

SELECT grp.GroupID, grp.GroupNumber, grp.Name, grp.Location, grp.GroupTypeID, grp.DivisionID, 
grp.MasterGroupID, grp.EffectiveDate, grp.TerminationDate
FROM [Group] grp 
WHERE 1 = 1 
AND grp.EffectiveDate = '1/1/2015 12:00:00 AM' AND grp.GroupTypeID = '2' 

为什么在使用多个表时我的查询无效?我专门在列之前引用了表别名(grp.EffectiveDate),所以我不明白还有什么问题。一如既往,感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

也许您的INNER JOIN之一应该是LEFT OUTER JOIN。当使用连接并且您希望返回包含/不包含子记录的父记录时,您的模式(可以为空的FK)允许这样做,那么您应该离开外连接。

SELECT grp.GroupID, grp.GroupNumber, grp.Name, grp.Location, grp.GroupTypeID, grp.DivisionID, 
grp.MasterGroupID, grp.EffectiveDate, grp.TerminationDate, crt.[ContractNumber], pln.[PBPNumber], div.SiteName, src.Name as SourceName 
FROM [Group] grp 
    INNER JOIN [IndividualPlanDemographic] idp ON grp.GroupID = idp.IndividualPlanDemographicID 
    INNER JOIN [Plan] pln ON idp.PlanID = pln.PlanID 
    INNER JOIN [Contract] crt ON pln.ContractID = crt.ContractID 
    --THE GROUP IS NOT REQUIRED TO BE IN A DIVISION RELATIONSHIP
    LEFT OUTER JOIN [Division] div ON grp.DivisionID = div.DivisionID 
    LEFT OUTER JOIN [SourceSystem] src ON div.SourceSystemID = src.SourceSystemID 
WHERE 1 = 1 
AND grp.EffectiveDate = '1/1/2015 12:00:00 AM' AND grp.GroupTypeID = '2' ORDER BY ContractNumber

答案 1 :(得分:1)

最终,这意味着与此日期和组类型匹配的行不包含您在INNER JOIN中的所有表中的记录。

您的数据库缺少预期记录,或者您需要将其中一些INNER JOIN更改为LEFT OUTER JOIN。