我有以下数据库架构:
table courses:
id
tutor_id
title
table course_categories:
id
category_id
course_id
table categories:
id
name
table tutors:
id
name
table subscribers:
id
course_id
user_id
我需要制作1个sql来获得所有类别的课程,以及该课程的导师和该课程的订阅者数量。这可以在1个查询中完成吗?应该使用存储过程吗?
答案 0 :(得分:5)
通过此查询,您可以获得所需内容:
select co.title as course,
ca.name as category,
t.name as tutor,
count(s.*) as total_subscribers
from courses co
inner join course_categories cc on c.id = cc.course_id
inner join categories ca on cc.category_id = ca.id
inner join tutors t on co.tutor_id = t.tutor_id
left join subscribers s on co.id = s.course_id
where co.title = 'Cat1'
group by co.title, ca.name, t.name
我在left join
上使用了subscribers
,因为给定的course
可能没有人。我假设所有其他表都包含每个course
,categorie
和tutor
的数据。如果没有,您也可以使用left join
,但之后您将拥有null数据。
答案 1 :(得分:1)
答案 2 :(得分:0)
从课程cou,course_categories cca,类别cat,tutors tu,subscriber sub中选择cou.title,cat.name,tu.name,count(sub.user_id),其中cou.id = cca.id和cat.id = tu.id和tu.id = sub.id group by cou.title,tu.name;