父/子自联接的MS Access数据结构问题

时间:2015-05-31 20:50:31

标签: sql ms-access-2013

我有一个包含以下表格的数据库:

  • BeliefsT

    • BeliefID(自动编号)
    • 信仰(短文)
  • ReasonsToAgreeT

    • ArgAgreeID(自动编号)
    • 结论AID(信仰查询)
    • ReasonToAgreeID(也是对BeliefsT的查询)
  • ReasonsToDisagreeT

    • ArgDisagreeID(自动编号)
    • 结论ID(也是对信仰的查找)
    • ReasonToDisagreeID(也是BeliefsT的查找)

问题1:我无法计算在ReasonsToAgreeT表中选择结论AID的次数。

这是我的第一次尝试:

SELECT BeliefsT.Belief, ReasonsToAgreeT.ReasonToAgreeID, ReasonsToDisagreeT.ReasonToDisagreeID
FROM (BeliefsT 
         LEFT JOIN ReasonsToAgreeT 
            ON BeliefsT.BeliefID = ReasonsToAgreeT.ConclusionAID
      ) LEFT JOIN ReasonsToDisagreeT 
            ON BeliefsT.BeliefID = ReasonsToDisagreeT.ConclusionDID
GROUP BY BeliefsT.Belief, ReasonsToAgreeT.ReasonToAgreeID, ReasonsToDisagreeT.ReasonToDisagreeID
ORDER BY BeliefsT.Belief;

它只是让你看看所有的值,但没有做任何事情......

我也可以一次看一张桌子,但这并没有给我带来任何好处:

SELECT ReasonsToAgreeT.ConclusionAID, Count(ReasonsToAgreeT.ReasonToAgreeID) AS CountOfReasonToAgreeID
FROM ReasonsToAgreeT
GROUP BY ReasonsToAgreeT.ConclusionAID;

对于我的报告数据源,这是我能得到的最接近的,但它会计算重复的空值,因为我的关系搞砸了:

SELECT BeliefsT.Belief, ReasonsToAgreeT.ReasonToAgreeID, ReasonsToDisagreeT.ReasonToDisagreeID
FROM (BeliefsT 
        LEFT JOIN ReasonsToAgreeT 
          ON BeliefsT.BeliefID = ReasonsToAgreeT.ConclusionAID
      ) LEFT JOIN ReasonsToDisagreeT 
          ON BeliefsT.BeliefID = ReasonsToDisagreeT.ConclusionDID;

当我包括同意表的原因和不同意表的原因时,关系变得混乱,因为他们都看着相同的信念表,并且它试图做一个交叉产品,一切都搞砸了,我无法准确计算同意或不同意的理由数量......

1 个答案:

答案 0 :(得分:0)

您的业务逻辑和问题定义有点不清楚,因此基于合格的猜测,您提供的最佳SQL查询解决方案如下:

SELECT BeliefsT.Belief, ReasonsToAgreeT.ReasonToAgreeID, ReasonsToDisagreeT.ReasonToDisagreeID FROM (BeliefsT LEFT JOIN ReasonsToAgreeT ON BeliefsT.BeliefID = ReasonsToAgreeT.ConclusionAID) LEFT JOIN ReasonsToDisagreeT ON BeliefsT.BeliefID = ReasonsToDisagreeT.ConclusionDID;

如果唯一的问题是错误地计算了Null个值,那么请引用相应字段添加WHERE子句Not Is Null。另一种选择是使用MS Access SQL条件运算符IIf(IsNull(SomeField), 0, 1)

希望这可能会有所帮助。最好的问候,