如何选择多个表?有6张桌子

时间:2018-04-05 13:16:50

标签: mysql sql

我有6张桌子

表国家 country_id | short_name

表用户(如果status = 1,则status = 2有效) id | country_id | status

表user_subscribed_disciplines id | user_id |discipline_id

表格训练 id | name

表user_subscribed_study_levels id | user_id | study_level_id

表study_levels id | name

如何用参数选择所有国家/地区?如何编写正确的sql查询?

   country | total users count | active users count | inactive users count | discipline subscribers count | top discipline | study level subscribers count | top study level
   USA     |       506         |          500       |     6                |    50                        |          PHD   |          90                   |  Social History
   CAN     |       406         |          406       |     0                |    50                        |          POS   |          0                   |  Social History

1 个答案:

答案 0 :(得分:1)

您正在寻找下面的查询:

select c.country_id
     , count(u.id) as TotalUsers
     , sum(case when u.status = 'active' then 1 else 0 end) as ActiveUsers
     , sum(case when u.status = 'Inactive' then 1 else 0 end) as InactiveUsers
     , (select count(*) from user_subscribed_disciplines) as DisciplineSubscribers
     , (select name from (select top 1 name,count(*) from disciplines group by name order by count(*) desc) t) as TopDiscipline
     , (select count*) from  user_subscribed_study_levels) as StudyLevelCount
     , (select name from (select top 1 name,count(*) from study_levels group by name order by count(*) desc) t) as TopStudyLevel
from countries c
inner join user u on u.country_id=c.country_id