我有3个表-表tblFactorDefinition,tblFamily和tblConstituent。
当尝试使用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)对应的因子值,
屏幕截图1是tblConstituent表, Secreenshot 2是tblFactorDefinition表, 屏幕快照3、4、5是tblFamily表:
答案 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 )