2013-12-10 85 views
0

所以我有以下表,users如何在查詢中創建MySQL查詢並連接?

+-----------+------------------+------+-----+---------+-------+ 
| 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和一列連接的數據。任何指針?

+0

*您可以使用* GROUP_CONCAT,雖然就個人而言,我更喜歡在應用層處理數組操作(有一點PHP的EG) – Strawberry

回答

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; 
+0

我可能更喜歡在JOIN一個子查詢,但這確實是一個解決方案。 –

+0

地雷更快;) – beiller

+0

我懶得把它作爲基準:-P –

4

您正在尋找GROUP_CONCAT。首先加入其他表格,以便可以獲取角色名稱,然後按用戶標識將它們組合在一起。

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