左加入关联表

时间:2011-10-21 16:46:05

标签: mysql

我需要帮助尝试加入使用关联表的表。

我有一个用户表

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

如何关联这两个表?

2 个答案:

答案 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

答案 1 :(得分: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