带有左连接帮助的Mysql子查询需要帮助

时间:2014-06-16 13:31:26

标签: php mysql sql join left-join

对于以下查询我无需帮助。查询工作正常,但有一点逻辑错误。我花了4个小时自己解决它但没有成功。

SELECT family_id, fees_term_id, fees_head_id, fees_head_name, full_name, fees_amount, paid FROM (
SELECT st.family_id, st.fees_head_id, st.fees_term_id, fh.fees_head_name, ft.full_name, 
SUM(st.fees_amount) AS fees_amount, SUM(fp.paid) AS paid
    FROM fees_students_setup st
    LEFT JOIN fees_head fh ON fh.fees_head_id = st.fees_head_id
    LEFT JOIN fees_term ft ON ft.fees_term_id = st.fees_term_id
    LEFT JOIN fees_paid fp ON fp.fees_head_id = st.fees_head_id
      AND fp.fees_term_id = st.fees_term_id
      AND st.family_id = fp.family_id
      AND fp.academic_start = st.academic_start
      AND fp.academic_end = st.academic_end
    WHERE st.family_id = '316'
    AND st.academic_start = '2013-04-01'
    AND st.academic_end = '2014-03-31'
    AND st.fees_term_id BETWEEN '1' AND '1'
    GROUP BY st.fees_head_id, st.fees_term_id
    ORDER BY st.fees_term_id
) st
;

此查询产生以下输出。 enter image description here 问题在于付费专栏。我有两张桌子(fee_setup)& (fees_paid)。在我的(费用设置)表中,两个家庭学生有两个入场费条目。当运营商支付一半费用。这是进入的两倍。在我的(fee_paid)表格中,有一个条目存在入场费= 1500.但是在输出中它会加倍,因为你可以在输出中看到。我知道为什么这个问题是由于群组声明造成的。请查看我的查询,如果有机会将fee_paid列加一次,请告诉我。我应该为此目的使用子查询吗?任何想法,请...

1 个答案:

答案 0 :(得分:1)

没有经过测试(没有足够的细节这么做),但是在子查询中加上费用之后再加上那个就会产生这样的结果: -

SELECT st.family_id, 
    st.fees_head_id, 
    st.fees_term_id, 
    fh.fees_head_name, 
    ft.full_name, 
    SUM(st.fees_amount) AS fees_amount, 
    fp.paid
FROM fees_students_setup st
LEFT JOIN fees_head fh ON fh.fees_head_id = st.fees_head_id
LEFT JOIN fees_term ft ON ft.fees_term_id = st.fees_term_id
LEFT JOIN 
(
    SELECT fees_head_id, fees_term_id, family_id, academic_start, academic_end, SUM(paid) AS paid
    FROM fees_paid
    GROUP BY fees_head_id, fees_term_id, family_id, academic_start, academic_end
) fp
ON fp.fees_head_id = st.fees_head_id
  AND fp.fees_term_id = st.fees_term_id
  AND st.family_id = fp.family_id
  AND fp.academic_start = st.academic_start
  AND fp.academic_end = st.academic_end
WHERE st.family_id = '316'
AND st.academic_start = '2013-04-01'
AND st.academic_end = '2014-03-31'
AND st.fees_term_id BETWEEN '1' AND '1'
GROUP BY st.fees_head_id, st.fees_term_id
ORDER BY st.fees_term_id

请注意,此处的GROUP BY不符合SQL标准。您应该包含所有非聚合列。在这种情况下,如果fee_head_id / fees_term_id组合有多个(例如)fees_head_name值,那么返回的fee_head_name值将是未定义的(可能是任何潜在值)。

在这种情况下,您可能只能将额外的列名添加到GROUP BY子句