Search code examples
mysqlgroup-concat

If there is a way to achieve this kind of result below using group_concat


Data

Brcode  name
1.      A
2.      A
3.      A

Expected result

Brcode  Name Common
1        A             1,2,3
2        A              1,2,3
3        A              1,2,3
 

Solution

  • Yes you can do a join.

    CREATE TABLE test_tbl        (
                 Brcode int(9),
                  name varchar(3) );
    
    
        INSERT INTO test_tbl VALUES (1,'A'),
                                    (2,'A'),
                                    (3,'A');
        
    
    SELECT t1.Brcode,
           t1.name,
           t2.common
    FROM test_tbl t1       
    inner join 
    (
      select name ,group_concat(Brcode  SEPARATOR ',') as Common from test_tbl group by name
    ) as t2 on t1.name=t2.name;
    

    Demo: https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/99

    Result: enter image description here