获取列的总和而不删除一些记录

getting sum of column and not delete some records

以下是表格中的一些数据

slm

id grade_level period
1 Grade 1 1st Grading Period
2 Grade 2 2nd Grading Period

slm_activities

id slmid activity count
1 1 77 5
2 2 72 6

时期

id period
1 1st Grading Period
2 2nd Grading Period
3 3rd Grading Period
4 4th Grading Period

活动

id activity
72 lesson
75 page
77 quiz

我需要为 mysql 获取这种输出,它将显示所有类型的活动和所有时间段,然后将它们的计数值相加,如果没有遇到其他活动,activitycount 将显示 0时期

activitycount activity period
5 quiz 1st Grading Period
0 quiz 2nd Grading Period
0 quiz 3rd Grading Period
0 quiz 4th Grading Period
0 lesson 1st Grading Period
6 lesson 2nd Grading Period
0 lesson 3rd Grading Period
0 page 1st Grading Period
0 page 2nd Grading Period
0 page 3rd Grading Period
0 page 4th Grading Period

这是我当前的 mysql 查询

SELECT SUM(count) AS activitycount, activities.activity, periods.period
FROM slm_activities 
LEFT JOIN activities ON activities.id = slm_activities.activity 
LEFT JOIN slm ON slm_activities.slmid = slm.id 
LEFT JOIN periods ON periods.period = slm.period
GROUP BY activities.activity, periods.period

由于您需要显示每个活动的所有时间段,因此您需要为此使用 CROSS JOIN。此外 table slm 应该存储 periods table 的 id 而不是 period 字段。

SELECT SUM(IFNULL(count, 0)) AS activitycount, activities.activity, periods.period
FROM activities
CROSS JOIN periods
LEFT JOIN slm ON periods.period = slm.period
LEFT JOIN slm_activities ON activities.id = slm_activities.activity
 AND slm.id = slm_activities.slmid
GROUP BY activities.activity, periods.period
ORDER BY activities.activity, periods.period;

结果

activitycount activity period
0 lesson 1st Grading Period
6 lesson 2nd Grading Period
0 lesson 3rd Grading Period
0 lesson 4th Grading Period
0 page 1st Grading Period
0 page 2nd Grading Period
0 page 3rd Grading Period
0 page 4th Grading Period
5 quiz 1st Grading Period
0 quiz 2nd Grading Period
0 quiz 3rd Grading Period
0 quiz 4th Grading Period

参见 this fiddle