修复加入多对多MySQL查询

时间:2012-12-19 18:31:29

标签: mysql sql join many-to-many

我有两个看起来像这样的表:

表A:

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

表B:

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

如图所示,Table A包含用户uID的属性数据,Table B包含用户uID的权限数据。

此刻,我正在使用,

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`

但它给了我一个结果:

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

我需要在查询中更改以获取:

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

1 个答案:

答案 0 :(得分:4)

GROUP_CONCAT需要其他参数,如其文档页面here中所述。

你想要的是distinct

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