一个用户
有很多资格
。我需要从 MySQL 数据库生成一个 Excel 电子表格。结果应为每个用户包含一行,同一行中包含他们的第 1、第 2 和第 3 资格的列。
用户表
id | Name
--------------
1 | James
2 | Bob
3 | Adam
4 | Michael
资格表
id | user_id | subject
-----------------------------------------
1 | 1 | English
2 | 2 | History
3 | 2 | Mathematics
4 | 2 | Biology
5 | 2 | Sports Science
6 | 2 | Art
7 | 3 | Physics
8 | 3 | Chemistry
10 | 4 | Geography
11 | 4 | Computer Science
12 | 4 | Theology
期望的结果
User ID | Name | Qualification 1 | Qualification 2 | Qualification 3
-----------------------------------------------------------------------
1 | James | English | NULL | NULL
2 | Bob | History | Mathematics | Biology
3 | Adam | Physics | Chemistry | NULL
4 | Michael | Geography | Computer Science | Theology
注意事项
- 我只需要每个用户的前 3 个资格。
- 用户可以拥有任意数量的资格。他们可能没有,也可能有 10 个。
- 在示例中,James 只有 1 个资格。 Bob 有 5 个。Adam 只有 2 个。
- 我只需要一个 SQL 解决方案,但最终目标是导出到 Excel(不相关,除非我可以在 Excel 中利用某些东西来简化此操作)。
- 这是一项一次性任务。我不需要经常这样做。
最佳答案
最简单的方法(MySQL 8.0 之前)使用变量和条件聚合:
select u.user_id, u.name,
max(case when rn = 1 then q.subject end) as qualification_1,
max(case when rn = 2 then q.subject end) as qualification_2,
max(case when rn = 3 then q.subject end) as qualification_3
from users u left join
(select q.*,
(@rn := if(@u = q.user_id, @rn + 1,
if(@u := q.user_id, 1, 1)
)
) as rn
from qualifications q,
(select @u := -1, @rn := 0) params
order by q.user_id, q.id
) q
on u.id = q.user_id
where rn <= 3
group by u.id, u.name
关于mysql - 加入每组中的前 3 条记录,并合并为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52317219/