Sven Richter
Sven Richter

Reputation: 423

mysql request using join and group_concat

I have three tables "names", "groups", "tasks"

"names"

| nid | name  |
|  1  | John  |
|  2  | Jim   |
|  3  | Jerry |

"groups"

| gid | nid |
|  1  |  1  |
|  1  |  2  |
|  2  |  2  |
|  2  |  3  |

"tasks"

| tid | gid |
|  1  |  2  |
|  2  |  1  |

I want to get a list of names, that belong to a task, like this:

| tid | names     |
|  1  | Jim,Jerry |
|  2  | John,Jim  |

I successfully tried:

SELECT t.tid,n.name
FROM tasks t
   LEFT JOIN groups g ON g.gid=t.gid
   LEFT JOIN names n ON n.nid=g.nid

This works so far, but the names are in single outputs so I tried to use GROUP_CONCAT(), but this does not work. I just get the first task with the wrong names!?!?

SELECT t.tid,GROUP_CONCAT(n.name)
FROM tasks t
   LEFT JOIN groups g ON g.gid=t.gid
   LEFT JOIN names n ON n.nid=g.nid

I have never used GROUP_CONCAT() before. It works well, when using it in a single SELECT without joins. A short explanation what I did wrong, would be nice.

Upvotes: 1

Views: 36

Answers (1)

Jean-François Savard
Jean-François Savard

Reputation: 21004

When using group_concat you need to group your results.

Add group by t.id at the end of your query.

Upvotes: 2

Related Questions