2011-10-21 96 views
1

我需要幫助試圖加入使用關聯表的表。左聯合關聯表

我有一個用戶表

Users Table 
user_id 
user_name 

Association Table 
user_id 
project_id 

Project Table 
project_id 
project_name 

我需要拉一個用戶,他們正在與相關項目的數量。

SELECT u.user_name, COUNT(p.project_id) projects 
FROM users u 
LEFT JOIN association a ON u.user_id = a.user_id 
GROUP BY u.user_name 

如何關聯兩個表?

+0

該查詢應該按原樣工作(儘管可以稍微改進)。這裏有什麼問題? – Jon

+0

出了什麼問題? –

回答

1

如果要關聯的項目和用戶,你需要做2聯接:

SELECT u.user_name, COUNT(p.project_id) projects 
FROM users u 
LEFT JOIN association a ON u.user_id = a.user_id 
LEFT JOIN projects p ON p.project_id = a.project_id 
GROUP BY u.user_name 

如果你想讓它快,你可以做:

SELECT u.user_name, COUNT(a.project_id) projects 
FROM users u 
LEFT JOIN association a ON u.user_id = a.user_id 
GROUP BY u.user_name 
+0

謝謝,這工作,但沒有加快我的網頁,因爲聯接更復雜,所以它的時間比個人查詢的總和更長。謝謝你的幫助。 – Thom

+0

@Thom,更新回答以加快查詢速度。 – Johan

0

我認爲你可以這樣做:

SELECT 
    Utbl.user_name, 
    NumTbl.numProjects 
FROM 
    UsersTable Utbl, 
    (SELECT 
     Atbl.user_id, 
     COUNT(*) AS numProjects 
    FROM 
     ProjectTable Ptbl, 
     AssociationTable Atbl 
    WHERE 
     Utbl.user_id = Atbl.user_id AND 
     Atbl.project_id = Ptbl.project_id) NumTbl 
WHERE 
    Utbl.user_id = NumTbl.user_id