1

我有以下数据库架构:

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 个查询中完成吗?这应该使用存储过程来完成吗?

4

3 回答 3

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 joinonsubscribers是因为给定的course. 我假设所有其他表都有每个course,categorie和的数据tutor。如果没有,您也可以使用用户left join,但是您将拥有 null 的数据。

于 2012-02-10T10:02:50.457 回答
1

可以办到。您需要查找select和使用join. 查看 选择加入以帮助完成作业

于 2012-02-10T10:03:03.037 回答
0

选择 cou.title, cat.name, tu.name, count(sub.user_id) from course cou, course_categories cca, categories cat,utors tu,subscribers sub where cou.id = cca.id and cat.id = tu.id tu.id = sub.id group by cou.title, tu.name;

于 2018-02-18T03:03:07.027 回答