skip to Main Content
ID title category
1 test a
1 test b
2 test2 c
2 test2 d
3 test3 e
3 test3 f

I have a table like above in mysql.
I want to group the "category" with the same ID as below.

ID title category
1 test a,b
2 test2 c,d
3 test3 e,f

I want to achieve this with mysql.
In that case, what kind of sql statement should be executed?

2

Answers


  1. SELECT 
      ID, 
      max(title) as title, 
      group_concat(category) as category
    FROM a
    GROUP BY ID
    

    You can also only repeat distinct values as such

    SELECT
      ID,
      group_concat(distinct title) as title,
      group_concat(distinct category) as category
    FROM a
    GROUP BY ID
    
    Login or Signup to reply.
  2. You can do it as follows :

    SELECT ID, title, group_concat(category) as category
    FROM mytable
    GROUP BY ID, title
    

    You can also use SEPARATOR and ORDER BY inside the GROUP_CONCAT function :

    SELECT ID, title, group_concat(category ORDER BY category ASC SEPARATOR ',') as category
    FROM mytable
    GROUP BY ID, title
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search