一个mysql表中的水平循环器

m0rkklqb  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(231)

这个问题在这里已经有答案了

如何在mysql中返回pivot表输出(9个答案)
两年前关门了。
我有一个mysql表:
每个用户有4封电子邮件:

id user_Id email
 1  11      emailx@email.com
 2  11      emailc@email.com
 3  11      emaild@email.com
 4  11      emailv@email.com
 5  12      emailr@email.com
 6  12      emailb@email.com
 7  12      emailW@email.com
 8  12      emailT@email.com
 9  13      emailJ@email.com
 10 13      emailI@email.com
 11 13      emailL@email.com
 12 13      emailQ@email.com

如何对行结果进行水平排序?
就像这样:

user_Id   email1           email2           email3             email4
 11        emailx@email.com emailc@email.com emaild@email.com   emailv@email.com
 12        emailr@email.com emailb@email.com emailW@email.com   emailT@email.com
 13        emailJ@email.com emailI@email.com emailL@email.com   emailQ@email.com
3zwjbxry

3zwjbxry1#

select user_Id , GROUP_CONCAT(email ORDER BY email) from tab
group by user_Id
rkue9o1l

rkue9o1l2#

如果你的电子邮件被限制在4个,那么你可以按照这个

select t1.user_id,
    (select email from test where test.user_id = t1.user_id limit 0,1) as email1,
    (select email from test where test.user_id = t1.user_id limit 1,1) as email2,
    (select email from test where test.user_id = t1.user_id limit 2,1) as email3,
    (select email from test where test.user_id = t1.user_id limit 3,1) as email4
from test t1
group by t1.user_id;

相关问题