简体   繁体   English

Select 每个分组列只有 2 行数据

[英]Select only 2 rows of data per grouped column

I have three tables in my database, for the purposes of discussion let's say they are:我的数据库中有三个表,出于讨论的目的,假设它们是:

USERS   
-----
id
display_name

ROLES
-----
id
role

USER_ROLES
----------
user_role_id
user_id
role_id

As you can see 1 user can have multiple roles.如您所见,1 个用户可以拥有多个角色。 Now I have successfully grouped them as their roles with the following query.现在,我已使用以下查询成功地将它们分组为他们的角色。

SELECT r.`name`, GROUP_CONCAT(u.display_name) AS users_for_role
FROM users u,
  roles r,
  user_roles ur
WHERE u.id = ur.user_id
  AND r.id = ur.role_id
GROUP BY r.id;

And got the result like并得到了类似的结果

| ROLE_USER         | user1,user6,user4 |
| ROLE_CELEBRITY    | user4,user5,user6 |
| ROLE_MUSICIAN     | user4             |

Now what I'm trying to achieve is I want to limit the select count to max 2. So my expected result would be ROLE_USER selects only "user1" and "user6" MAX现在我想要实现的是我想将 select 计数限制为最大 2。所以我的预期结果是 ROLE_USER 只选择“user1”和“user6”MAX

One trick you could use here would be to just wrap your current call to GROUP_CONCAT with SUBSTRING_INDEX , to retain only at most the first two entries:您可以在这里使用的一个技巧是仅使用SUBSTRING_INDEX包装您当前对GROUP_CONCAT的调用,最多只保留前两个条目:

SELECT r.name, SUBSTRING_INDEX(GROUP_CONCAT(u.display_name), ',', 2) AS users_for_role
FROM users u
INNER JOIN roles r ON u.id = ur.user_id
INNER JOIN user_roles ur ON r.id = ur.role_id
GROUP BY r.id;

Another more formal approach would be to use a subquery with ROW_NUMBER to restrict to the first two entries per name:另一种更正式的方法是使用带有ROW_NUMBER的子查询来限制每个名称的前两个条目:

WITH cte AS (
    SELECT r.id, r.name, u.display_name,
           ROW_NUMBER() OVER (PARTITION BY r.name ORDER BY u.display_name) rn
    FROM users u
    INNER JOIN roles r ON u.id = ur.user_id
    INNER JOIN user_roles ur ON r.id = ur.role_id
)

SELECT name, GROUP_CONCAT(display_name) AS users_for_role
FROM cte
WHERE rn <= 2
GROUP BY id;

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

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