Jump to content

LEFT JOIN to a subquery


emedal63

Recommended Posts

Hi, I'm trying to left join an employee table to a subqueried-trainings table.

 

Employees Table:

$query= "SELECT * FROM employees WHERE employees.department='Oncology'";

ID -- NAME -- DEPARTMENT

123 -- Joe -- Oncology

456 -- Mary -- Oncology

789 -- Alex -- Oncology

 

Trainings Table:

$query = "SELECT trainings.id, GROUP_CONCAT(subject) FROM trainings GROUP BY trainings.cid";

This query is necessary to get one row for each ID and the training SUBJECT concated in the following column

ID -- SUBJECT

001 -- apple, orange

123 -- apple, orange, pear

789 -- orange, pear

 

How do I write a LEFT JOIN so that I get all the people from employees table, then add the SUBJECT column to  the matching ID? The result should look like this:

ID -- NAME -- DEPARTMENT -- SUBJECT

123 -- Joe -- Oncology -- apple, orange, pear

789 -- Alex -- Oncology -- orange, pear

 

Many thanks!!!

Link to comment
Share on other sites

Thanks mikosiko, your suggestion kind of works. It's giving me a list of all the employees (not just Oncology) and it applies the GROUP_CONCAT to just the Oncology employees. The result looks like:

ID -- NAME -- DEPARTMENT

012 -- Mary -- Surgery

123 -- Joe -- Oncology -- apple, orange, pear

127 -- Rich -- Finance

789 -- Alex -- Oncology -- orange, pear

 

Can the query be modiefied so that the result shows ONLY Oncology employees AND it applies the GROUP_CONCAT to those employees?

Link to comment
Share on other sites

Thanks mikosiko. It looks like using just JOIN gives me an inner join where it will only give me ID's that exist on both the emloyees table and trainings table. It's the best solution so far. However, if an employee has NOT done a training, the name won't show up in the result.

 

I think LEFT JOIN is what I need, but I can't get it to play nicely with GROUP_CONCAT. Any other ideas?

 

Thanks again for all your help!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.