简体   繁体   English

MySQL使用Group By来限制结果

[英]MySQL using Group By to limit results

Okay, so I am trying to perform a query that has 4 tables, users, events, event_roles, user_event_role. 好的,所以我试图执行一个包含4个表,用户,事件,event_roles,user_event_role的查询。

The users can fill multiple roles. 用户可以填充多个角色。 What i am trying to do is get a result that looks more like this: User, event, Role(s) 我想要做的是得到一个看起来更像这样的结果:用户,事件,角色

So if user 'Bill' is associated with event 'Meeting' and 'Bill' Fills multiple roles instead of getting a result like this: 因此,如果用户'Bill'与事件'Meeting'和'Bill'相关联,则填充多个角色而不是获得如下结果:

user   event     role
--------------------------
bill   Meeting   admin
bill   Meeting   director

how would I get my result to be like this 我怎么能得到这样的结果呢?

user   event     role    role
----------------------------------
bill   Meeting   admin   director

Here is a query that I'm trying to build off of. 这是我正在尝试构建的查询。

Select * 
  FROM `users` u 
LEFT JOIN `event_role` er ON u.user_id = er.user_id 
LEFT JOIN `events` e ON er.event_id = e.event_id

The result you seek is not possible. 您寻求的结果是不可能的。

However there is something close: 然而,有一些接近:

SELECT
  user,
  event,
  group_concat(role SEPARATOR ',') as roles
FROM
  `users` u 
  LEFT JOIN `event_role` er
    ON u.user_id = er.user_id 
  LEFT JOIN `events` e
    ON er.event_id = e.event_id
GROUP BY u.user_id

which would yield: 会产生:

user   event     roles
----------------------
bill   Meeting   admin,director

In either case you would need to adjust your logic to parse it correctly. 在任何一种情况下,您都需要调整逻辑以正确解析它。

You cannot get such result, because you don't know how many roles there might be (ie columns count), but you can use GROUP_CONCAT that way: 你不可能得到这样的结果,因为你不知道可能有多少角色(即列数),但你可以这样使用GROUP_CONCAT

SELECT *,
GROUP_CONCAT(event_roles.role SEPARATOR ',') as roles
FROM users
LEFT JOIN event_role USING(user_id)
LEFT JOIN events USING(user_id)
GROUP BY user_id

Using this query you will get all roles concatonated with , . 使用此查询,您将获得所有角色, But be aware of limitation of GROUP_CONCAT , the default value is set to 1024 characters which might not be enough (see my.cnf ). 但要注意GROUP_CONCAT的限制,默认值设置为1024个字符,这可能不够(请参阅my.cnf )。

Use Group_concat ( http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html ) like this. 像这样使用Group_concat( http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html )。 To show that quickly, I'm using a database from the excellent MySQL intro book by Ben Forta ( http://www.forta.com/books/0672327120/ ), no affiliation. 为了快速展示,我正在使用Ben Forta( http://www.forta.com/books/0672327120/ )出色的MySQL介绍书中的数据库,没有任何从属关系。

SELECT v.vend_id, GROUP_CONCAT(p.prod_id)
FROM products p 
JOIN  vendors v ON v.vend_id= p.vend_id
JOIN  orderitems oi ON oi.prod_id = p.prod_id
GROUP BY v.vend_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM