简体   繁体   中英

Combine two complex SQL statements into one

I have the following 2 SQL statements:

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 ;

Is it possible to combine the two queries based on the country.id field so I have only one result with #Projects, #Consultants and Country Name?

You could join the country table on two aggregate queries on the other tables:

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

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