简体   繁体   English

修复加入多对多MySQL查询

[英]Fixing Joined Many-to-Many MySQL Query

I have two tables that look like this: 我有两个看起来像这样的表:

Table A: 表A:

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

Table B: 表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 . 如图所示, Table A保存用户uID属性数据, Table B保存用户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 |
+-------+------------+----------+

GROUP_CONCAT takes additional arguments, as explained on its documentation page here . GROUP_CONCAT需要额外的参数,因为它的文档页的说明这里

The one you want is distinct : 你想要的是distinct

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM