Search code examples
phpmysqlgroup-concat

MySQL group concat used with 2 join table query results duplicate


I have joined 2 tables and use group concat to get data on some coloumns. below is my query. this returns same row twice

SELECT GROUP_CONCAT(  vehicles.role ORDER BY vehicles.id ASC SEPARATOR '\n') as role,GROUP_CONCAT(  vehicles.size ORDER BY vehicles.id ASC SEPARATOR '\n') as size,festivals.id,festivals.ref_no as ref_no, festivals.camping,festivals.tour_mgr_name,festivals.email,festivals.mobile,festivals.name_address, GROUP_CONCAT( namedesgs.name  ORDER BY namedesgs.id ASC SEPARATOR '\n') as names,GROUP_CONCAT( namedesgs.designation  ORDER BY namedesgs.id ASC SEPARATOR '\n') as designations
FROM festivals
    LEFT JOIN namedesgs  ON festivals.id = namedesgs.festival
    LEFT JOIN vehicles  ON festivals.id = vehicles.festival 
Group BY festivals.id

please advice how to get data without duplicates?

when i used DISTINCT with concat . it does not work for below

ex:

namedesg data

enter image description here

vehicles data

enter image description here

current output

but on my output veicles data has duplicates 3 times even though one data exist.

here is query i tried

SELECT t.id, GROUP_CONCAT(a.name SEPARATOR '\n') as name,
 GROUP_CONCAT(a.designation SEPARATOR '\n') as desg ,GROUP_CONCAT(b.role SEPARATOR '\n') as role,
 GROUP_CONCAT(b.size SEPARATOR '\n') as size
FROM festivals t
 LEFT JOIN namedesgs a ON a.festival=t.id 
 LEFT JOIN vehicles b ON b.festival=t.id  
where t.id=4
GROUP BY t.id


festivals

id ref_no
1   AAA
2   BBB
3   CCC

namedesgs  

id name designation festival(festival table id)
1  ann   SE              1
2  ben   AE              1
3  Jan   cook            1
4  alun  cook            1
5  hej    hik            2
6  nij    AE             1

vehicles

id role size   festival(festival table id)
1  r1   14              1
2  r1   12              1
3  r2   12              1
4  r3  12              1
5  r4    12            2

what i want as out put is

festivalid name designations role  size
1           ann    SE          r1  14
            ben    AE          r1  12
           jan    cook         r2  12
           alun    cook        r3  12
           aij    AE          
2          hej    hik         r4   12

Solution

  • For what you want, you can't put name and designation, and role and size, in separate columns in the results. You need to concatenate them before using GROUP_CONCAT. And use DISTINCT to remove duplicates.

    SELECT t.id AS festivalid, 
            GROUP_CONCAT(DISTINCT CONCAT(a.name, ' ', a.designation) SEPARATOR '\n') AS `name designations`,
            GROUP_CONCAT(DISTINCT CONCAT(b.role, ' ', b.size) SEPARATOR '\n') AS `role size`
    FROM festivals AS t
    LEFT JOIN namedesgs a ON a.festival=t.id 
    LEFT JOIN vehicles b ON b.festival=t.id
    GROUP BY t.id