从存储过程结果中删除重复的列行并连接其他列[重复]
Posted
技术标签:
【中文标题】从存储过程结果中删除重复的列行并连接其他列[重复]【英文标题】:Remove Duplicate Column Rows from Stored Procedure Result and concatenate other column [duplicate] 【发布时间】:2021-09-07 04:45:42 【问题描述】:我有这个存储过程的代码:
BEGIN
SELECT teams.name,
IFNULL(users.email,'N/A') as email,
IFNULL(users.name,'N/A') as user_name,
IFNULL(team_user.role,'N/A') as role
FROM teams
LEFT JOIN team_user ON teams.id=team_user.team_id
LEFT JOIN users ON team_user.user_id=users.id
WHERE role is NULL
OR role='admin';
END
我想在表格中显示存储过程的结果。以下是它显示的表格示例:
Team Name | User Name |
---|---|
Team1 | AdminUser1ForTeam1 |
Team1 | AdminUser2ForTeam1 |
Team 2 | AdminUser1ForTeam1 |
Team3 | AdminUser1ForTeam3 |
Team3 | AdminUser2ForTeam3 |
这个表的问题是,如果一个团队有超过 1 个管理员,团队名称将在两个单独的行中重复。以下是我想要达到的结果:
Team Name | User Name |
---|---|
Team1 | AdminUser1ForTeam1, AdminUser2ForTeam1 |
Team 2 | AdminUser1ForTeam1 |
Team3 | AdminUser1ForTeam3, AdminUser2ForTeam3 |
我尝试使用 group_concat 但是无法检测到团队名称何时重复。 我也可以使用php来尝试并达到结果。非常感谢任何帮助!
【问题讨论】:
【参考方案1】:使用聚合。我怀疑你真的想要:
SELECT t.name,
COALESCE(GROUP_CONCAT(u.email), 'N/A') as email,
COALESCE(GROUP_CONCAT(u.name), 'N/A') as user_name,
COALESCE(GROUP_CONCAT(tu.role), 'N/A') as role
FROM teams t LEFT JOIN
team_user tu
ON t.id = tu.team_id AND tu.role = 'admin' LEFT JOIN
users u
ON tu.user_id = u.id
GROUP BY t.name
【讨论】:
以上是关于从存储过程结果中删除重复的列行并连接其他列[重复]的主要内容,如果未能解决你的问题,请参考以下文章