0

I have table with two columns user_id and tags.

  user_id    tags
    1    <tag1><tag4>
    1    <tag1><tag2>
    1    <tag3><tag2>
    2    <tag1><tag2>
    2    <tag4><tag5>
    3    <tag4><tag1>
    3    <tag4><tag1>
    4    <tag1><tag2>

I want to merge this two records into one record like this.

  user_id    tags
    1    tag1, tag2, tag3, tag4
    2    tags, tag2, tag4, tag5
    3    tag4, tag1
    4    tag1, tag2

How can i get this? Can anyone help me out. Also need to convert tags field into array []. I don't have much knowledge on typical sql commads. I just know the basics. I am a ruby on rails guy.

Ashwin Yaprala
  • 2,737
  • 2
  • 24
  • 56

3 Answers3

1

You should look into the GROUP_CONCAT function in mysql.A good example is here

In your case it would be something like:

SELECT user_id, GROUP_CONCAT(tags) FROM tablename GROUP BY user_id
Prahalad Gaggar
  • 11,389
  • 16
  • 53
  • 71
Cargo23
  • 3,064
  • 16
  • 25
  • 1
    Its not something you can do readily in SQL, as you are talking about pulling apart data within a field. If you had originally limited the tags field to just 1 tag, you would be able to do it. – Cargo23 May 21 '13 at 18:40
  • @ashwinkumar to get unique/sorted tags, you have to use a sub-select and then do the GROUP_CONCAT against just the unique row.s – Cargo23 Jan 23 '17 at 16:35
1

duplicate of https://stackoverflow.com/questions/16218616/sql-marching-values-in-column-a-with-more-than-1-value-in-column-b/16218678#16218678

select user_id, group_concat(tags separator ',')
from t
group by user_id
Community
  • 1
  • 1
ulkas
  • 5,748
  • 5
  • 33
  • 47
0

Try this one -:

SELECT t2.userid,
stuff((
SELECT ', ' + t1.tags
FROM table_name as t1
where t1.userid = t2.userid
FOR XML PATH('')
), 1, 2, '')
FROM table_name as t2
GROUP BY t2.userid

I hope this helps you out.

Check the example -: http://www.sqlfiddle.com/#!3/85c89/6

Rebika
  • 179
  • 5