开发者

Need SQL help returning a dynamic dataset

I've got three tables I would like to query for a single dataset. Here is what I've got so far:

SELECT u.Name, r.Description from Users u 
JOIN UserRoleMembership m ON m.UserID = u.UserID
JOIN UserRoles r ON r.开发者_如何学编程RoleID = m.RoleID
GROUP BY u.UserID

The problem is that the above query only returns the first Role. How can I get the User.Name and a list of Roles on a single row?

Users (Distinct Users)

INSERT into Users (UserID, Name) Values
(0, Me),
(1, Me2);

UserRoles (Distinct Role, and Role description)

INSERT into Users (RoleID, Description) Values
(0, Everyone),
(1, Users),
(2, Admin);

UserRoleMembership (one user may have more than one role)

INSERT into UserRoleMembership (MembershipID, UserID, RoleID) Values
(0, 0, 0),
(1, 0, 1),
(2, 1, 0),
(3, 1, 2);


Group by the fields you want to see. In this case, group by u.name, r.description instead of grouping by userid.

It is a would-be-handy feature from MySQL, which is actually very confusing I think. Most DBs wouldn't even allow this query. You should not be able to have fields in your select that are not in the group by, unless you aggregate them somehow (use min or max or so).

[edit]

If you want the descriptions in a single row per user, group by userid (of rather u.name), and use GROUP_CONCAT(r.Description) to aggregate the roles.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜