mysqlsqlquery-performance

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?


Solution

  • 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.