Reputation: 243
Not understanding how to use the GROUP_CONCAT function as my queries seem to repeat values that I don't actually want.
I have three tables:
------------------
Content
------------------
cid | title
2334 | Lorem Ipsum
------------------
Organizers
------------------
cid | name | sort
2334 | John Doe | 0
------------------
Participants
------------------
cid | name | sort
2334 | Jane Doe | 0
2334 | Bob Hope | 1
2334 | Bart Simpson | 2
I'm trying to write a query that will produce:
cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe | Jane Doe, Bob Hope, Bart Simpson
So, I'm trying to use GROUP_CONCAT. But, values are being repeated, so I'm not sure how to output the results I'm looking for?
SELECT GROUP_CONCAT(co.name) as organizers,
GROUP_CONCAT(cp.name) FROM content n
LEFT JOIN organizers co ON n.cid = co.cid
LEFT JOIN participants cp ON n.cid = cp.cid
WHERE n.cid = 2334
The above yields:
cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe, John Doe, John Doe | Jane Doe, Bob Hope, Bart Simpson
Upvotes: 0
Views: 2071
Reputation: 838
SELECT n.cid, n.Title,
GROUP_CONCAT(DISTINCT co.name ORDER BY co.sort) as organizers,
GROUP_CONCAT(cp.name ORDER BY cp.sort)
FROM Content n
LEFT JOIN Organizers co ON n.cid = co.cid
LEFT JOIN Participants cp ON n.cid = cp.cid
GROUP BY n.cid
Upvotes: 1
Reputation: 47331
select group_concat(distinct co.name)
details : http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
syntax
GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val])
Upvotes: 2