2

I have a mysql table:

Each user have 4 emails:

 id user_Id email
 1  11      [email protected]
 2  11      [email protected]
 3  11      [email protected]
 4  11      [email protected]
 5  12      [email protected]
 6  12      [email protected]
 7  12      [email protected]
 8  12      [email protected]
 9  13      [email protected]
 10 13      [email protected]
 11 13      [email protected]
 12 13      [email protected]

How to sort the row result horizontally?

Like that:

 user_Id   email1           email2           email3             email4
 11        [email protected] [email protected] [email protected]   [email protected]
 12        [email protected] [email protected] [email protected]   [email protected]
 13        [email protected] [email protected] [email protected]   [email protected]
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
jeanpaul
  • 21
  • 1

2 Answers2

2

If your emails are limited to 4 then you can follow this

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;
DEarTh
  • 975
  • 1
  • 7
  • 18
1
select user_Id , GROUP_CONCAT(email ORDER BY email) from tab
group by user_Id 
starko
  • 1,150
  • 11
  • 26