2016-04-22 126 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執行工作。 –