在搜索中梳理mysql外连接

时间:2012-12-20 19:51:06

标签: mysql join

我的数据库中有3个表

PROJECTS
- id
- name
- date_created
- user_created
- status (or for disabled, 1 for enabled)

PROJECTS_MANAGERS (a project may have 0 or more managers)
- id
- project_id
- manager_username

PROJECTS_MEMBERS (a project may have 0 or more members)
- id
- project_id
- member_username

我正在尝试创建一个mysql连接查询,以列出特定用户所处的状态等于1的所有项目。具体来说,这个查询将列出所有项目,其中用户名为“bob”。 “use_created”,“manager_username”或“member_username”字段以及projects.status字段为1的位置。但诀窍是可能有多个管理员或成员具有相同的project_id(当然,这里有不同的ID和member_usernames)。

我已经尝试过这段代码了,但它似乎没有用(在where子句中给我错误'1054未知列'projects.status'。我试过做一个“完全加入”,但我来学习mysql不支持这个:

SELECT *
FROM
    `projects` as theProjects

LEFT OUTER JOIN
    projects_managers
            AS theManagers
                    ON theProjects.id = theManagers.project_id
WHERE
    projects.status = 1
UNION ALL

SELECT *
FROM
    `projects` as theProjects
RIGHT OUTER JOIN
    projects_members
            AS theMembers
                    ON theProjects.id = theMembers.project_id
        WHERE
    projects.status = 1

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

怎么样:

SELECT projects.*
FROM projects
LEFT JOIN projects_managers managers ON managers.project_id=projects.id
LEFT JOIN projects_members members ON members.project_id=projects.id
WHERE status=1 AND
      (user_created="bob" OR managers.username="bob" OR members.username="bob")
GROUP BY projects.id