MySQL group concat用于2个连接表查询结果重复

时间:2017-04-19 17:07:39

标签: php mysql group-concat

我已加入2个表并使用group concat获取某些coloumns的数据。下面是我的查询。这会两次返回同一行

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

请告知如何获取没有重复的数据?

当我使用带有concat的DISTINCT时。它不适用于下面的

前:

namedesg数据

enter image description here

车辆数据

enter image description here

当前输出

但是在我的输出数据中,即使存在一个数据,数据也会重复3次。

这是我试过的查询

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

我想要的是什么

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

1 个答案:

答案 0 :(得分:1)

根据您的需要,您不能将namedesignation以及rolesize放在结果的不同列中。在使用GROUP_CONCAT之前,您需要连接它们。并使用DISTINCT删除重复项。

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