Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate data from one field, in a comma-delimited list, in a many-to-many relationship in MySQL?

I have a many-to-many relationship between People and Departments since one person can be in many departments.

People          Departments
------          -----------
pID  pName      deptID   deptName
1    James      1        Engineering
2    Mary       2        Research
3    Paul       3        Marketing
                4        Communications

People_Departments
------------------
pID   deptID
1     1
1     2
2     2
2     4
3     1
3     2
3     3

What I want is this:

pName  deptName
James  Engineering, Research
Mary   Research, Communication
Paul   Engineering, Research, Marketing

If I do plain LEFT JOINs on the tables using the SQL below, I will get several rows related to one person:

SELECT people.pName,
       departments.deptName
FROM people
LEFT JOIN people_departments ON people.pID=people_departments.pID
LEFT JOIN departments ON people_departments.deptID=departments.deptID

I have tried various combinations of GROUP_CONCAT but without luck.

Any ideas to share?

like image 375
Shailen Avatar asked Jul 24 '11 21:07

Shailen


People also ask

How do I concatenate comma separated values in SQL?

Concatenate Rows Using COALESCE All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How to pass comma separated values in MySQL query?

In MySQL, you can return your query results as a comma separated list by using the GROUP_CONCAT() function. The GROUP_CONCAT() function was built specifically for the purpose of concatenating a query's result set into a list separated by either a comma, or a delimiter of your choice.


1 Answers

    SELECT people.pName,
           GROUP_CONCAT(departments.deptName SEPARATOR ', ') deptName
      FROM people
 LEFT JOIN people_departments 
        ON people.pID = people_departments.pID
 LEFT JOIN departments 
        ON people_departments.deptID = departments.deptID
  GROUP BY people.pID

Output:

+-------+----------------------------------+
| pName | deptName                         |
+-------+----------------------------------+
| James | Engineering, Research            |
| Mary  | Research, Communications         |
| Paul  | Engineering, Research, Marketing |
+-------+----------------------------------+
3 rows in set (0.00 sec)
like image 63
Shef Avatar answered Oct 09 '22 10:10

Shef