如何在sql中使用group concat连接三个表

时间:2016-05-06 08:28:48

标签: php mysql sql json join

我正在尝试使用group concat连接三个表.Problem是主表以json格式加入列。

查询正在运行,但一次又一次地重复加入列数据 查询 - >

[SELECT tour_package.description AS description, 
         tour_package.NAME AS NAME, 
         GROUP_CONCAT( destination_continent.NAME ) AS continent_name,
         GROUP_CONCAT( travel_style.NAME ) AS travel_style_name,
         tour_package.id AS id, 
         tour_package.img_path_thumb AS img_path_thumb, 
         tour_package.continent_id, 
         tour_package.travel_style_id
FROM tour_package
LEFT JOIN destination_continent ON 
      FIND_IN_SET( destination_continent.id, 
           REPLACE( REPLACE( REPLACE( tour_package.continent_id,  '\[',  '' ) ,  '\]',  '' ) ,  '\"',  '' ) ) 
LEFT JOIN travel_style ON 
      FIND_IN_SET( travel_style.id, 
           REPLACE( REPLACE( REPLACE( tour_package.travel_style_id,  '\[',  '' ) ,  '\]',  '' ) ,  '\"',  '' ) ) 
WHERE  `tour_package`.`DELETE` = 0 &&  `destination_continent`.`DELETE` = 0
LIMIT 0 , 30][1]

表格 - > image1

image2

image3

2 个答案:

答案 0 :(得分:0)

在GROUP_CONCAT函数中使用DISTINCT关键字

I.e:

SELECT tour_package.description AS description, 
       tour_package.NAME AS NAME, 
       GROUP_CONCAT(DISTINCT destination_continent.NAME ) AS continent_name,
       GROUP_CONCAT(DISTINCT travel_style.NAME ) AS travel_style_name,
       tour_package.id AS id, 
       tour_package.img_path_thumb AS img_path_thumb, 
       tour_package.continent_id, 
       tour_package.travel_style_id
.... 

答案 1 :(得分:0)

Group Concatenating进行Distinct检查

[SELECT tour_package.description AS description, tour_package.NAME AS NAME, GROUP_CONCAT( DISTINCT(destination_continent.NAME) ) AS continent_name, GROUP_CONCAT( DISTINCT(travel_style.NAME) ) AS travel_style_name, tour_package.id AS id, tour_package.img_path_thumb AS img_path_thumb, tour_package.continent_id, tour_package.travel_style_id FROM tour_package LEFT JOIN destination_continent ON FIND_IN_SET( destination_continent.id, REPLACE( REPLACE( REPLACE( tour_package.continent_id,  '\[',  '' ) ,  '\]',  '' ) ,  '\"',  '' ) )  LEFT JOIN travel_style ON FIND_IN_SET( travel_style.id, REPLACE( REPLACE( REPLACE( tour_package.travel_style_id,  '\[',  '' ) ,  '\]',  '' ) ,  '\"',  '' ) )  WHERE  `tour_package`.`DELETE` =0 &&  `destination_continent`.`DELETE` =0 LIMIT 0 , 30][1]