2016-04-21 70 views
1

我有以下2个SQL语句:组合两个复杂的SQL语句到一个

Select count(project.id) as '# Projects', c2.name as ' Country name' from project, country c2, project_country where project_country.project_id = project.id and project_country.country_id= c2.id group by c2.name; 


select count(user.id) as '# Consultants',c1.name as ' Country name' from user,consultant_profile, country c1 where c1.id= user.country_id and user.is_active=1 and user.type=0 and user.id = consultant_profile.user_id group by country.name ; 

是否有可能基于该country.id场合并这两个查询,所以我只有一个结果与#Projects,#Consultants和国名?

回答

1

你可以加入country表上的两个聚集查询在其他表:

SELECT c.name AS country_name, num_projects, num_consultants 
FROM country c 
JOIN (SELECT pc.country_id, COUNT(p.id) AS num_projects 
     FROM  project p 
     JOIN  project_country pc ON p.id = pc.projcet_id 
     GROUP BY pc.country_id) x ON x.country_id = c.id 
JOIN (SELECT u.country_id, COUNT(u.id) AS num_consultants 
     FROM  user u 
     WHERE u.is_active = 1 AND u.type = 0 
     GROUP BY u.country_id) y ON y.country_id = c.id 
+0

谢谢@Mureinik,正是我需要的。 –