如何在查询中创建MySQL查询并连接?

时间:2013-12-10 17:23:43

标签: mysql

所以我有下表users

+-----------+------------------+------+-----+---------+-------+
| Field     | Type             | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| uid       | int(10) unsigned | NO   | PRI | 0       |       |
| name      | varchar(60)      | NO   | UNI |         |       |
---------------------------------------------------------------

表格roles

+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| rid   | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(64)      | NO   | UNI |         |                |
+-------+------------------+------+-----+---------+----------------+

我有第三个表users_roles,它在一对多关系中将users映射到一个或多个roles

+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| uid   | int(10) unsigned | NO   | PRI | 0       |       |
| rid   | int(10) unsigned | NO   | PRI | 0       |       |
+-------+------------------+------+-----+---------+-------+

最后,我有第四个表格memberships,与users一对一地映射:

+-------------------+---------------+------+-----+---------+-------+
| Field             | Type          | Null | Key | Default | Extra |
+-------------------+---------------+------+-----+---------+-------+
| membership_no     | varchar(32)   | NO   | PRI | NULL    |       |
| uid               | int(11)       | YES  |     | NULL    |       |
--------------------------------------------------------------------

目前我有一个简单易用的查询,它提供了一个用户名列表:

SELECT u.uid, u.name, m.membership_no FROM users AS u 
LEFT JOIN memberships AS m ON u.uid = m.uid;

但是现在我想在我的查询中添加一个额外的列,每个用户查找一次users_roles个条目,然后在一列中连接每个roles.name,这样我就能看到所有的该用户的角色。示例输出可能是:

uid    name       membership no    roles
---    ----       -----            ------
1      foo        123432           admin, normal user, student
2      bar baz    235235           admin
3      bak        2352352          normal user, student

所以我的任务是如何在users_roles表上集成此附加查询,将user_roles.rid链接到roles.rid并在列中连接数据。有什么指针吗?

2 个答案:

答案 0 :(得分:4)

您正在寻找GROUP_CONCAT。首先加入其他表,以便获取角色名称,然后按用户ID将它们组合在一起。

SELECT u.uid, u.name, m.membership_no, GROUP_CONCAT(r.name ORDER BY r.rid) AS roles
FROM users AS u 
LEFT JOIN memberships AS m ON u.uid = m.uid
JOIN users_roles AS ur ON u.uid = ur.uid
JOIN roles AS r ON ur.rid = r.rid
GROUP BY u.uid

DEMO:http://sqlfiddle.com/#!2/ffa31/1

答案 1 :(得分:3)

使用MySQL GROUP_CONCAT功能。

SELECT 
u.uid, 
u.name, 
m.membership_no,
(SELECT GROUP_CONCAT(name) FROM users_roles ur INNER JOIN roles r ON r.rid = ur.rid WHERE ur.uid = u.uid) as roles
FROM users AS u 
LEFT JOIN memberships AS m ON u.uid = m.uid;