简体   繁体   中英

Getting all of the fields using SQL Join

So Here is my problem. I have multiple tables that I need to pull data from.

A Project table

Project id project name etc

Project Needs table

need id need

Need to projects table

project id need id

volunteer table (aka members)

all the member data

member_skills table

member_id skill_id (aka need for projects)

here is my query:

$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";

It pulls all of the information correctly, but I have been unable to figure out how to pull all of the project needs. Right now it only pulls the needs that I have a volunteer match for. Basically, I want to pull those (as skills) and pull the project needs (as needs)

It's hard to answer without some sample data and expected output.

This can happen if all values of project_needs are not in project_needs_to_projects table. As you are using JOIN , it trys to return records with matching values in both tables on left and right side of the JOIN .

Using RIGHT JOIN for project_needs instead of JOIN will return all values from project_needs and matching values + null values from project_needs_to_projects table. You query will look like

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')...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM