0

这是我无法弄清楚的。我可以让一个连接正常工作。我可以让超过 2 个表工作的​​唯一方法是在循环中使用嵌套查询。如何从具有多个连接的单个查询中获取结果,但不从我的主表中获取多个列表。

3个表:用户:2个用户;项目:2个项目;技能:6个技能;

这里使用 Codeigniter,所以我会放 CI 语法。

$this->db->select('*');
    $this->db->from('projects');
    $this->db->join('user', 'user.id = projects.project_principal_id','left');
    $this->db->join('projects_skills_bridge', 'projects_skills_bridge.ps_project_id = projects.project_id','right');
    //$this->db->group_by('project_id'); // removed the multiple listing problem caused by the above JOIN
    $sql = $this->db->get();

现在,当我遍历并获取我的项目(包含用户和技能信息)时,我应该只得到 2 个项目。我能弄清楚如何获得与该项目相关的技能的唯一方法是在循环中使用嵌套查询(没有上面的第二个 JOIN),但我知道这很草率。如果我使用 GROUP 子句,我只会得到我想要的 2 个项目,但只有第一个技能而不是我想要的几个。

输出应如下所示:

用户 Bob 的 Project Alpha - 技能:吉他、键盘、贝斯

用户 Sally 的项目 Beta - 技能:写作、html、发票

我确定这是一个菜鸟问题,所以提前感谢您查看。

4

1 回答 1

0

你似乎有类似的东西:

 -- user [id] is named [name]
users(id,name)
-- project [project_id] named [project_name] is by user [project_principal_id]
projects(project_id,project_name,project_principal_id)
-- project [ps_project_id] requires skill [skill]
projects_skills_bridge(ps_project_id,skill)

也许你想要这些 (project_name,name,skill) 行:

THERE_EXISTS id, project_id, project_principal_id,ps_project_id
    user [id] is named [name]
AND project [project_id] named [project_name] is by user [project_principal_id]
AND project [ps_project_id] requires skill [skill]
AND id = project_principal_id
AND ps_project_id = project_id

如果是这样,那么只需在您当前的查询中更改'left'和。(你为什么使用和?)'right''inner''left''right'

SELECT project_name, name, skill
FROM user
JOIN projects ON user.id = projects.project_principal_id
JOIN projects_skill_bridge ON projects_skills_bridge.ps_project_id = projects.project_id

如果您希望每个项目有一行及其(可能是单个)主体及其所有技能的字符串,那么您需要对(内部)联接进行分组,以便每个 project_id 的每个技能有一行,然后选择 project_name、name 和 GROUP_CONCAT(skill )。

SELECT project_name, name, GROUP_CONCAT(skill) AS skills
FROM user
JOIN projects ON user.id = projects.project_principal_id
JOIN projects_skill_bridge ON projects_skills_bridge.ps_project_id = projects.project_id
GROUP BY id, project_id

选择的 GROUP BY 列确保每个 project_id 的每个技能只有一行,假设 id 和 project_id 是其基表中的键。

于 2014-09-02T05:59:57.763 回答