I have the following DB structure (I know, its not the greatest structure but it is what it is):
users
| id | company |
| -------| -------- |
| user1 | company1 |
| user2 | company2 |
------
users_companies
| user_id| company |
| -------| -------- |
| user1 | company3 |
| user1 | company4 |
| user2 | company5 |
| user2 | company6 |
I need to write a query that will return the following result set
| user1 | company1 |
| user1 | company3 |
| user1 | company4 |
| user1 | company1,company3,company4 |
| user2 | company2 |
| user2 | company5 |
| user2 | company6 |
| user2 | company2,company5,company6 |
As you can see for each user it will individually list out each company and also create an aggregate row of all their companies they are assigned to. I have this working in a redshift query but I'm stuck on how to get this same result using MySQL. Any help would be much appreciated!
Here is the working redshift query that I have.
with u as (
select *
from users
union all
select *
from users_companies
)
select id, company
from (
select id, Company, 1 seq
from u
union all
select id, string_agg(company, ','), 2 seq
from u
group by Id, seq
)t
order by Id, seq, company;