2016-04-22 81 views
3

我有以下两个查询:SQL:结合两个查询到一个单一的一个

Select count(project.id) as num_project , 
      industry.name as industry_name 
    from project, project_industry, industry 
    where industry.id= project_industry.industry_id and 
      project.id = project_industry.project_id 
    group by industry.id; 

Select count(user.id) as num_consultants , 
     industry.name as industry_name 
from consultant_profile, industry_experience,user, industry 
where industry_experience.consultant_profile_id = consultant_profile.id 
     and industry_experience.industry_id= industry.id 
     and user.type=0 
     and user.is_active=1 
     and consultant_profile.user_id=user.id 
group by industry_id; 

我试图将它们组合成一个单一的一个如下:

SELECT i.name AS industry_name, num_projects, num_consultants 
FROM industry i 
JOIN (SELECT pc.industry_id, COUNT(p.id) AS num_projects 
     FROM  project p 
     JOIN  project_industry pc ON p.id = pc.project_id 
     GROUP BY pc.industry_id) x ON x.industry_id = i.id 
JOIN (SELECT y.industry_id, COUNT(u.id) AS num_consultants 
     FROM  user u, consultant_profile cp 
     JOIN  project_experience pe on pe.consultant_profile_id = cp.id 
     WHERE u.is_active = 1 AND u.type = 0 
     GROUP BY y.industry_id) z ON z.industry_id = i.id; 

但似乎没有工作。有人能指出我做错了什么吗?任何帮助深表感谢。

编辑:要说清楚第一个查询显示与每个行业相关的项目数量。第二个查询显示与每个行业相关的顾问数量。

我想第三个查询,以显示从同一表中的第一两个查询上3个单独的列中的信息:行业名称,#Projects,#Consultants

表结构是如下,其中 - >描述该表的主键和外键:

Project -> project.id 
Project_industry -> project_industry.id, project_id, industry_id 
Industry -> industry.id 

user -> user.id 
Consultant_profile -> consultant_profile.id, user_id 
Industry_Experience -> industry_experience.id, consultant_profile_id, industry_id 
Industry -> industry.id 
+0

你能告诉我们你的表结构,你想要得到的输出? – Aurel

+0

结合如何?向我们显示您想要组合的两个查询中的几行,以及组合结果。 – jarlh

+0

你确定你的第二个查询是正确的吗?请交叉检查'我'是否是任何表的别名 – saikumarm

回答

2

你几乎每下面查询我的理解there.As应该为你工作。

QUERY

select T1.industry_name ,num_project ,num_consultants from 
(Select count(project.id) as num_project , industry.name as industry_name ,industry.id as id from project, project_industry, industry where industry.id= project_industry.industry_id and project.id = project_industry.project_id group by industry.id) T1 
JOIN 
(Select count(user.id) as num_consultants , industry.name as industry_name,industry.id as id from consultant_profile, industry_experience,user, industry where industry_experience.consultant_profile_id = consultant_profile.id and industry_experience.industry_id= industry.id and user.type=0 and user.is_active=1 and consultant_profile.user_id=user.id group by industry_id) T2 
ON T1.id = T2.id 
+0

感谢您的回复,不幸的是您实施了以下错误:错误代码:1054.'on子句'中的未知列'T1.industry.id' –

+0

@MarcZaharescu ,这个查询是否终止?因为它看起来是一样的,但用一个稍微不同的语法编写。 –

+0

是的@Shirish执行工作。 –