JOIN拉出比预期多2倍的行

时间:2019-05-13 15:55:04

标签: sql sql-server-2012

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

  • tblFactorDefinition在FieldName列中具有带有对应因子的FamilyID(即Factor1,Factor2,..... Factor9)
  • 表tblConstituent具有Family中每个组成部分的关联的Factors值(如果存在Factor1,Factor2,.. Factor9的值),并且可以通过tbLFacctorDefinition中的FamilyID与FamilyID进行连接。
  • 表tblFamily具有“家庭”详细信息。 (即FamilyTypeID = 1为Index或FamilyTypeID = 2为ETF)。

当尝试使用tblConstituent中的与因子相对应的因子值检索FamilyID时,我得到了2-3倍的行数。例如,FamilyID = 10216具有27975个成分,但是我的查询获取了超过55k +行。我在墙上试图弄清楚JOIN。

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)对应的因子值,

tblConstituent

tblFactorDefinition

tblFamily tblFamily tblFamiliy

屏幕截图1是tblConstituent表, Secreenshot 2是tblFactorDefinition表, 屏幕快照3、4、5是tblFamily表:

1 个答案:

答案 0 :(得分:0)

将联接更改为“左外部联接”,然后使用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 )