1

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

表 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 |
+-------+------------+----------+
4

1 回答 1

4

GROUP_CONCAT需要额外的参数,如其文档页面中所述。

你想要的是distinct

SELECT GROUP_CONCAT(distinct `a`.`attr`) AS `attrs` . . .
于 2012-12-19T18:33:55.650 回答