Search code examples
mysqlsqlgroup-concat

Selecting multiple rows of data from a subtable along with the parent row table in MySQL


I have two tables in my database roughly laid out as below

Client

id |  other data
1  |  data 1
2  |  data 2
3  |  data 3
4  |  data 4

Employee assigned

id  | clientid | employee
1   | 1        | Fred
2   | 1        | Jim
3   | 3        | Peter
4   | 4        | Fred
5   | 4        | Peter
6   | 4        | James

Is there a way to return the client table with all of the employee records from the employee table? Ideally I would want both the id of the row and the employee name so I don't think I can use GROUP_CONCAT to collect more than one column. There is also no guarantee that there will always be an entry for each client in the employee table so it would need to return an empty/null result for those clients.

I have tried two ways to get this so far in php, both are pretty inefficient in one way or another.

(A) The first was to effectively make a new database connection half way through the first one to return the list of employees associated with that client id but obviously that results in a significant number of database connections being made for just one query.

(B) The second was to pull the entire employee table into an array at the beginning of the code and search through that array to pull out the rows relating to that client id which then have the employee name and row id in. Over time this is going to end up with a pretty large array being dumped into php instantly.

Is there some way of pulling this out using just a single SQL query? I'm not all that fussed how the data would come out as I am sure I could sort through it in the php at the other end, but perhaps something along the lines of

Results

id |  other data | employees
1  |  data 1     | 1,Fred;2,Jim
2  |  data 2     | 
3  |  data 3     | 3,Peter
4  |  data 4     | 4,Fred;5,Peter;6,James

If this has been asked before somewhere I apologise, but I have been searching around a bit over the last week and haven't found all that much to help.


Solution

  • SELECT e.*, c.other_data FROM Employee e
    INNER JOIN Client c ON e.client_id = c.id
    

    So, what you end up with is all the information from both tables grabbed in one query. So, the data would be:

         id        client_id    Employee    other_data
         1             1          Fred        data 1
         2             1          Jim         data 1
         3             3          Peter       data 3
         4             4          Fred        data 4
         5             4          Peter       data 4
         6             4          James       data 4