3

我的数据库中有 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 unknown column '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

任何帮助将不胜感激。

4

1 回答 1

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
于 2012-12-20T20:11:17.210 回答