所以我有以下表,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
和一列連接的數據。任何指針?
*您可以使用* GROUP_CONCAT,雖然就個人而言,我更喜歡在應用層處理數組操作(有一點PHP的EG) – Strawberry