使用SQL Join获取所有字段

时间:2015-08-25 14:02:25

标签: php mysql join multiple-tables

所以这是我的问题。我有多个表需要从中提取数据。

项目表

项目ID 项目名 等

项目需求表

需要身份证明 需要

需要项目表

项目ID 需要id

志愿者表(又名成员)

所有会员资料

member_skills表

member_id skill_id(又称需要项目)

这是我的查询:

$query = "INSERT INTO PROJECT_NOTIFY_TEMP (project_id, project_name, volunteer_name, volunteer_email, volunteer_skills)
SELECT p.project_id as PROJECT_ID, p.project_name as PROJECT_NAME, CONCAT(m.first_name,' ',m.last_name) as FULL_NAME, m.email as EMAIL, GROUP_CONCAT(DISTINCT pn.need ORDER BY pn.need SEPARATOR ', ') as NEED
FROM PROJECTS p
JOIN project_needs_to_projects pntp
ON (pntp.project_id = p.PROJECT_ID)
JOIN project_needs pn
ON (pntp.need_id = pn.need_id AND pn.active = 'Y')
JOIN member_skills ms
ON (pn.need_id = ms.skill_id)
JOIN members m
ON (ms.member_id = m.member_id)
WHERE p.PROJECT_ID = '".$PROJECT_ID."' 
GROUP BY m.member_id";

它正确地提取了所有信息,但我一直无法弄清楚如何满足所有项目需求。现在它只能满足我有志愿者匹配的需求。 基本上,我想拉动那些(作为技能)并拉动项目需求(作为需求)

1 个答案:

答案 0 :(得分:0)

如果没有一些样本数据和预期的输出,很难回答。

如果project_needs的所有值都不在project_needs_to_projects表中,则会发生这种情况。当您使用JOIN时,它会尝试在JOIN的左侧和右侧的两个表中返回具有匹配值的记录。

使用RIGHT JOIN代替project_needs代替JOIN将返回project_needs中的所有值以及来自project_needs_to_projects表的匹配值+空值。您的查询将类似于

SELECT p.project_id as PROJECT_ID, p.project_name as PROJECT_NAME,
CONCAT(m.first_name,' ',m.last_name) as FULL_NAME, m.email as EMAIL,
GROUP_CONCAT(DISTINCT pn.need ORDER BY pn.need SEPARATOR ', ') as NEED
FROM PROJECTS p
    JOIN project_needs_to_projects pntp
    ON (pntp.project_id = p.PROJECT_ID)
    RIGHT JOIN project_needs pn
    ON (pntp.need_id = pn.need_id AND pn.active = 'Y')...