简体   繁体   中英

How to get data from 4 tables in 1 sql query?

I have the following database schema:

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

I need to make 1 sql to get a course with all it's categories, and the tutor for that course and the number of subscribers for that course. Can this be done in 1 query? Should this be done using stored procedures?

With this query you get what you want:

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

I used left join on subscribers because there might be no one for a given course . I'm assuming that all the other tables have data on it for every course , categorie and tutor . If not, you can user left join as well but then you'll have data with null.

It can be done. You need to look up select and the use of join . See select and join to help complete the assignment

从课程cou,course_categories cca,类别cat,导师tu,订阅者sub中选择cou.title,cat.name,tu.name,count(sub.user_id),其中cou.id = cca.id和cat.id = tu.id和tu.id = sub.id按cou.title,tu.name分组;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM