我正在使用桌子。为了说明的话:
mysql> SELECT users.id, username, REPLACE(selected_groups, '\r', ', '), groups.id, groups.label FROM users LEFT JOIN groups ON users.selected_groups;
+----+------------------------+--------------------------------------+------+---------------+
| id | username | REPLACE(selected_groups, '\r', ', ') | id | label |
+----+------------------------+--------------------------------------+------+---------------+
| 7 | Greg | 1, 2, 3, | 1 | Administrator |
| 7 | Greg | 1, 2, 3, | 2 | Member |
| 7 | Greg | 1, 2, 3, | 3 | Banned |
| 8 | Steve | 1, 2, | 1 | Administrator |
| 8 | Steve | 1, 2, | 2 | Member |
| 8 | Steve | 1, 2, | 3 | Banned |
| 9 | Steve The Banned Admin | 1, 3, | 1 | Administrator |
| 9 | Steve The Banned Admin | 1, 3, | 2 | Member |
| 9 | Steve The Banned Admin | 1, 3, | 3 | Banned |
| 10 | Example man | 1, 2, 3, | 1 | Administrator |
| 10 | Example man | 1, 2, 3, | 2 | Member |
| 10 | Example man | 1, 2, 3, | 3 | Banned |
+----+------------------------+--------------------------------------+------+---------------+
12 rows in set (0.00 sec)
如您所见,我有一个用户表和一个组表。在users表中有一个'selected_groups'列,其中使用返回的分隔值('\ r')定义相关的组。
问题是我不能确定如何在标签字段中返回每个必需的标签。结果输出最好是这样的:
+----+------------------------+--------------------------------------+------+-------------------------------+
| id | username | REPLACE(selected_groups, '\r', ', ') | id | groups.label |
+----+------------------------+--------------------------------------+------+-------------------------------+
| 7 | Greg | 1, 2, 3, | 1 | Administrator, Member, Banned |
| 8 | Steve | 1, 2, | 1 | Administrator, Member |
| 9 | Steve The Banned Admin | 1, 3, | 1 | Administrator, Banned |
| 10 | Example man | 1, 2, 3, | 1 | Administrator, Member, Banned |
+----+------------------------+--------------------------------------+------+-------------------------------+
你认为这是可能的,如果是的话,有没有人对我有任何提示/解决方案?
非常感谢, 瑞奇
答案 0 :(得分:1)
您应该查看group_concat。
在用户ID和用户名上加group by
子句,在标签上加group_concat
,就可以了。
我在想:
SELECT users.id, username, REPLACE(selected_groups, '\r', ', '), GROUP_CONCAT(DISTINCT groups.label)
FROM users
LEFT JOIN groups ON users.selected_groups;
GROUP BY users.id, username
(这未经过测试,因此可能需要进行一些修改)
编辑:我从查询中删除了groups.id,因为它没有任何意义。