如何从两个具有多对多关系的MySQL表中对列进行求和

时间:2013-08-27 00:09:26

标签: mysql many-to-many

我需要检索每个学生的值,如下所示

student full name | costs | discounts | net Value | payments | remaining

当我尝试

SELECT 
    concat_ws(' ',students.firstname,students.secondname,students.thirdname,students.forthname,students.lastname),
        students.birthdate,
        sum(costs.value),
        sum(discounts.value),
        sum(costs.value)-sum(discounts.value),
        sum(payments.amount),
        sum(costs.value)-sum(discounts.value)-sum(payments.amount)     

FROM students
JOIN coststudents 
       ON  coststudents.student_id = students.student_id 
 JOIN costs  
    ON  costs.cost_id = coststudents.cost_id
JOIN discountstudent 
       ON  discountstudent.student_id = students.student_id 
JOIN discounts  
    ON  discounts.id = discountstudent.id
JOIN payments 
       ON  payments.student_id = students.student_id 

它只给我一行,并且不对应于查询。 请帮忙。

1 个答案:

答案 0 :(得分:1)

在代码末尾放置GROUP BY students.student_id。

编辑:而不是JOIN使用LEFT JOIN。