我在名为tbl_enrolments(id, student_id, semester_id, unit_id, date)
的表中有五列。在这里,我只需要根据此表中的相同unit_id
计算相同semester_id
的数量。到目前为止,这就是我尝试过的方法。
SELECT e.unit_id, COUNT(e.unit_id) as count,
u.unit_title,
u.unit_name,
s.sem_name
FROM tbl_enrolments e
INNER JOIN tbl_unit_of_study u
ON e.unit_id = u.id
INNER JOIN tbl_semesters s
ON e.semester_id = s.id
GROUP BY e.unit_id
此处,此查询正在计算来自所有不同unit_id
的所有相同semester_id
。但是我需要用相同的unit_id
来计算所有相同的semester_id
。我该怎么办?
我的桌子是这样的:
答案 0 :(得分:2)
检查这是否在寻找您的内容,是否对您有帮助-
mysql> select semester_id, count(unit_id) from tbl_enrolments group by semester_id;
+-------------+----------------+
| semester_id | count(unit_id) |
+-------------+----------------+
| 2 | 5 |
| 1 | 8 |
| 12 | 2 |
+-------------+----------------+
3 rows in set (0.00 sec)
mysql> select semester_id, unit_id, count(unit_id) from tbl_enrolments group by semester_id, unit_id;
+-------------+---------+----------------+
| semester_id | unit_id | count(unit_id) |
+-------------+---------+----------------+
| 2 | 3 | 3 |
| 2 | 1 | 2 |
| 1 | 2 | 2 |
| 1 | 6 | 2 |
| 1 | 4 | 4 |
| 12 | 1 | 1 |
| 12 | 6 | 1 |
+-------------+---------+----------------+
7 rows in set (0.00 sec)
mysql> select semester_id, unit_id, count(unit_id) from tbl_enrolments group by semester_id, unit_id having semester_id = 2;
+-------------+---------+----------------+
| semester_id | unit_id | count(unit_id) |
+-------------+---------+----------------+
| 2 | 3 | 3 |
| 2 | 1 | 2 |
+-------------+---------+----------------+
2 rows in set (0.00 sec)
mysql> select semester_id, unit_id, count(unit_id) from tbl_enrolments group by semester_id, unit_id having semester_id = 2 and unit_id = 3;
+-------------+---------+----------------+
| semester_id | unit_id | count(unit_id) |
+-------------+---------+----------------+
| 2 | 3 | 3 |
+-------------+---------+----------------+
1 row in set (0.00 sec)