如何在没有多个列表的情况下加入3个表?

时间:2014-08-21 02:41:14

标签: php mysql codeigniter nested-query

这是我无法弄清楚的。我可以让一个加入工作正常。如果我在循环中使用嵌套查询,我可以获得超过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项目Alpha   - 技能:吉他,键盘,低音

用户Sally的项目测试版   - 技能:写作,HTML,发票

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

1 个答案:

答案 0 :(得分: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(技能)。

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是其基表中的键。