首页 > 解决方案 > JOIN 拉取的行数比预期的多 2 倍

问题描述

我有 3 个表 - 表 tblFactorDefinition、tblFamily 和 tblConstituent。

在尝试使用 tblConstituent 中的 Factors corrosponding Factors Value 检索 FamilyID 时,我得到了 2-3 倍的行数。例如,FamilyID =10216 有 27975 个成分,但我的查询获取超过 55k+ 行。我正在尝试找出加入的方法。

SELECT DISTINCT tc.FamilyID, 
                tfd.FieldName, 
                tc.Factor1, 
                tc.Factor2, 
                tc.Factor3, 
                tc.Factor4, 
                tc.Factor5, 
                tc.Factor6, 
                tc.Factor7, 
                tc.Factor8, 
                tc.Factor9, 
                tf.OpenDate 
FROM   soladbserver..tblFamily tf 
       JOIN soladbserver..tblFactorDefinition tfd 
         ON tfd.FamilyID = tf.FamilyID 
       JOIN soladbserver..tblConstituent tc 
         ON tc.FamilyID = tf.FamilyID 
            AND tc.StartDate <= Getdate() 
            AND tc.EndDate > Getdate() 
WHERE  tf.OpenDate = Cast(Getdate() AS DATE) 
       AND tf.FamilyTypeID = 1 
       AND tf.DataProviderID = 2 
       AND tf.FamilyID IN ( 10216 ) 

我期待 27975 行具有对应的 FieldName Factor1, Factor2,...,Factor9) 的因子值,因为它们都有值。

tbl成分

tblFactor 定义

tbl家庭 tbl家庭 tbl家庭

截图 1 为 tblConstituent 表,截图 2 为 tblFactorDefinition 表,截图 3,4,5 为 tblFamily 表:

标签: sqlsql-server-2012

解决方案


将join改为“Left Outer Join”,使用sql子查询select语句拉取字段名,看看得到了什么。如果 FamilyID 是 tc 表中的主键和其他表中的外键,这应该可以让您到达您想要的位置。

SELECT tf.FamilyID, 
            (Select top 1 isNull(tfd.FieldName,'') from soladbserver..tblFactorDefinition tfd 
     where tfd.FamilyID = tf.FamilyID ) as FieldName, -- this assumes each familyID only has one tfd.FieldName -- if not change both to left outer joins and leave the rest as is and run it
            tc.Factor1, 
            tc.Factor2, 
            tc.Factor3, 
            tc.Factor4, 
            tc.Factor5, 
            tc.Factor6, 
            tc.Factor7, 
            tc.Factor8, 
            tc.Factor9, 
            tf.OpenDate 
FROM   soladbserver..tblFamily tf 
  left outer JOIN soladbserver..tblConstituent tc 
     ON tc.FamilyID = tf.FamilyID 
        AND tc.StartDate <= Getdate() 
        AND tc.EndDate > Getdate() 
WHERE  tf.OpenDate = Cast(Getdate() AS DATE) 
   AND tf.FamilyTypeID = 1 
   AND tf.DataProviderID = 2 
   AND tf.FamilyID IN ( 10216 ) 

推荐阅读