如果有人可以帮助我,我会遇到一些SQL查询的麻烦。所以我有学生,参与,课程,地点,student_to_courses 这些表格。我需要让所有学生参与到特定课程中,并且我正在使用此查询
select
s.name as student_name, c.name as course_name, p.name as place_name
from
student_to_courses s2c,
students_participation sp,
students s,
courses c,
places p
where
s.id = s2c.participation_id AND
s.id = sp.profile_id AND
c.id = s2c.course_id AND
p.id = c.place_id = p.id AND
s2c.course_id = 1
但我需要计算学生在特定地方的次数,例如 student_name,course_name,place_name,| 3 | 。现在,我正在使用另一个查询,我每次在循环中调用它。但我想知道是否有办法只用单一查询来做到这一点。提前感谢所有想帮助我的人。
答案 0 :(得分:1)
您可以执行COUNT(),然后对其余列进行GROUP BY:
select s.name as student_name,
c.name as course_name,
p.name as place_name,
count(*)
from students s
inner join student_to_courses s2c on s.id = s2c.participation_id
inner join courses c on c.id = s2c.course_id
inner join places p on p.id = c.place_id
inner join students_participation sp on s.id = sp.profile_id
where s2c.course_id = 1
group by s.name,c.name,p.name
我还将连接更改为显式连接,因为更容易阅读容易出错的错误。
答案 1 :(得分:0)
试试这个:
select
s.name as student_name, c.name as course_name,
p.name as place_name, count(*) qtd
from
student_to_courses s2c,
students_participation sp,
students s,
courses c,
places p
where
s.id = s2c.participation_id AND
s.id = sp.profile_id AND
c.id = s2c.course_id AND
p.id = c.place_id = p.id AND
s2c.course_id = 1
group by s.name, c.name, p.name
count(*)
是AGGREGATE FUNCTION请参阅此链接以了解。