3

I have a table of 2 columns, user_id and connection_type. Both the fields are not unique. One single user id can appear many times and one single connection type can appear many times. How will I group all the connection types to one single user id?

Table I have:

schema: 
user_id -- INT 
connection_type -- STRING

user_id connection_type 
101     4g 
102     3g 
101     4g 
101     2g 
102     2g 
101     4g 
102     4g 
101     4g 
102     4g 
101     4g

Table I need from the above:

user_id connection_type 
101     ['4g','4g','2g','4g','4g','4g'] 
102     ['3g','2g','4g','4g']
3
  • Show us your code so we can help. Commented Apr 30, 2020 at 13:15
  • Consider handling this in application code Commented Apr 30, 2020 at 13:29
  • doesn't appear to be anything in the data that would guarantee a particular order of elements in the array. from the data shown, looks like 102 ['4g','2g','4g','3g'] (the elements in a different order ) would be equally valid. (before someone says this is not an answer to the question that was asked, that's why i posted this as a comment and not an answer) Commented Apr 30, 2020 at 13:47

2 Answers 2

3

MySQL does not natively support arrays - but if you want a JSON array you can do:

select user_id, json_arrayagg(connection_type) connection_types
from mytable
group by user_id
Sign up to request clarification or add additional context in comments.

Comments

1

you can use group_concat function in MySQL:

query is below:

select user_id,
group_concat(",",Connection_type) as connecttion_type
from table
group by user_id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.