sql - JOIN 拉取的行数比预期的多 2 倍
问题描述
我有 3 个表 - 表 tblFactorDefinition、tblFamily 和 tblConstituent。
- tblFactorDefinition 的 FamilyID 与 FieldName 列中的对应因子(即 Factor1,Factor2,.....Factor9)
- 表 tblConstituent 具有家族中每个成分的关联因子值(Factor1、Factor2、..Factor9 的值,如果存在),并且可以通过 FamilyID 与 tbLFacctorDefinition 中的 FamilyID 连接。
- 表 tblFamily 具有家庭详细信息。(即 FamilyTypeID=1 是索引或 FamilyTypeID=2 是 ETF)。
在尝试使用 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) 的因子值,因为它们都有值。
截图 1 为 tblConstituent 表,截图 2 为 tblFactorDefinition 表,截图 3,4,5 为 tblFamily 表:
解决方案
将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 )
推荐阅读
- python - 如何使用 2 y 缩放轴和共享 X 轴进行绘图?
- node.js - 如何创建 app.use() 将数据库中的数据附加到 res 对象
- c - .C 接口的 Rcpp 包装器
- go - 如何在 http.Get Request 中使用双引号和冒号作为查询字符串?
- java - 关闭连接以防止 Java/ADF 中的泄漏
- java - 如何修复“找不到类型 [entity] 的属性 [repositoryMethod]!” 我什么时候使用继承实体的存储库?
- linux - Bash 脚本在第一次运行时总是失败,然后在重新运行后成功(粘贴命令)
- python - Project Euler # 81 最小路径总和 ** 代码为一个案例产生正确的结果,而为另一个案例产生错误的结果
- firebase - 如何在没有身份验证的情况下向 Firestore 添加安全规则?
- javascript - 导航问题 - 无法对未安装的组件执行 React 状态更新