在SQL中加入三个表

时间:2011-03-23 10:57:18

标签: mysql sql

User
uid name

Roles
uid role_id

Subscriptions
uid subscriptions_id

好吧,这看起来似乎太容易了,但我们都未能得到希望的结果,这应该是这样的:

user roles subscriptions
1    2,3   1,4,5
2    2,4   4,5,6
....

相反,结果如下:

user roles subscriptions
1    2,3   5
2    2,4   6
....

select命令如下所示:

SELECT User.name, 
       GROUP_CONCAT(Roles.role_id), 
       GROUP_CONCAT(Subscriptions.subscriptions_id) 
FROM   User 
       LEFT JOIN Roles ON User.uid = Roles.uid 
       LEFT JOIN Subscriptions ON Users.uid = Subscriptions.uid

btw - GROUP_CONCAT不是问题。如果我把它留下来,我仍然会得到这样的东西:

user roles subscriptions
1    2     5
1    3     5
2    2     6

而不是

user roles subscriptions
1    2     1
1    3     4
1    -     5

2 个答案:

答案 0 :(得分:0)

我试过了:

SELECT User.uid, 
       GROUP_CONCAT(DISTINCT Roles.role_id), 
       GROUP_CONCAT(DISTINCT Subscriptions.subscriptions_id)
FROM   User 
       LEFT JOIN Roles ON User.uid = Roles.uid 
       LEFT JOIN Subscriptions ON User.uid = Subscriptions.uid
GROUP BY User.uid

我得到了这个:

user    roles    subscriptions
1       2,3      1,5,4
2       2,4      4,5,6

这是你的结果吗?

答案 1 :(得分:0)

select
 u.uid, u.name, r.roles_grp_concat, s.subs_grp_concat
from
 users u
left outer join
(
   select uid, group_concat(role_id) as roles_grp_concat
   from roles group by uid
) r on r.uid = u.uid
left outer join
(
   select uid, group_concat(subscriptions_id) as subs_grp_concat
   from subscriptions group by uid
) s on s.uid = u.uid
order by
 u.uid;