[英]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. 我需要制作1条sql才能获得一门具有所有类别的课程,以及该课程的导师和该课程的订户数量。 Can this be done in 1 query? 可以在1个查询中完成吗? 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
. 我在subscribers
上使用了left join
,因为给定的course
可能没有人。 I'm assuming that all the other tables have data on it for every course
, categorie
and tutor
. 我假设所有其他表格在每course
, categorie
和tutor
上都有数据。 If not, you can user left join
as well but then you'll have data with null. 如果没有,您也可以用用户left join
,但是您的数据将为空。
从课程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分组;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.