topherg
topherg

Reputation: 4303

Fixing Joined Many-to-Many MySQL Query

I have two tables that look like this:

Table A:

+-----+-----+------+-------+
| aID | uID | attr | value |
+-----+-----+------+-------+
| 1   | 1   | fn   | john  |
+-----+-----+------+-------+
| 2   | 1   | ln   | smith |
+-----+-----+------+-------+
| 3   | 2   | fn   | jim   |
+-----+-----+------+-------+
| 4   | 2   | ln   | bean  |
+-----+-----+------+-------+

Table B:

+-----+-----+-------+-------+
| bID | uID | perm  | value |
+-----+-----+-------+-------+
| 1   | 1   | admin | 1     |
+-----+-----+-------+-------+
| 2   | 2   | news  | 1     |
+-----+-----+-------+-------+
| 3   | 2   | cms   | 1     |
+-----+-----+-------+-------+

As it shows, Table A holds attribute data for a user uID, and Table B holds permission data for a user uID.

At the moment, I am using,:

SELECT GROUP_CONCAT(`a`.`attr`) AS `attrs`
     , GROUP_CONCAT(`a`.`value`) AS `values`
     , GROUP_CONCAT(`b`.`perm`) AS `perms` 
FROM `a` 
JOIN `b` 
ON `a`.`uID` = `b`.`uID` 
GROUP BY `a`.`uID`, `b`.`uID`

But it is giving me a result:

+-------------+-------------------+-------------------+
| attrs       | values            | perms             |
+-------------+-------------------+-------------------+
| fn,ln       | John,Smith        | admin,admin       |
+-------------+-------------------+-------------------+
| fn,fn,ln,ln | Jim,Jim,Bean,Bean | news,cms,news,cms |
+-------------+-------------------+-------------------+

What do I need to change in my query to get:

+-------+------------+----------+
| attrs | values     | perms    |
+-------+------------+----------+
| fn,ln | John,Smith | admin    |
+-------+------------+----------+
| fn,fn | Jim,Bean   | news,cms |
+-------+------------+----------+

Upvotes: 1

Views: 105

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270713

GROUP_CONCAT takes additional arguments, as explained on its documentation page here.

The one you want is distinct:

SELECT GROUP_CONCAT(distinct `a`.`attr`) AS `attrs` . . .

Upvotes: 4

Related Questions