mySQL GROUP_CONCAT IN JOIN

时间:2014-04-17 07:39:54

标签: mysql join group-concat

我有以下SQL。我试图在Join中执行GROUP_CONCAT,但无论我怎么看,它似乎都无法正常工作。

本质上,有一个链接标记表在另一个包含标记的表上执行一对多。所以可能会有一个文章记录的8个标签。我需要他们连在一起.vs。最终得到8条记录。

SELECT 
  `articles`.`art_title`,
  `articles`.`art_bodytext`,
  `info`.`inf_start_date`,
  `info`.`inf_end_date`,
  `info`.`inf_hits`,
  `info`.`inf_acl`,
  `category`.`name`,
  `options`.`opt_tpl`,
  `options`.`opt_published`,
  `options`.`opt_options`,
  `options`.`opt_acl`,
  `tags`.`tag`
FROM
  `linktable`
  INNER JOIN `articles` ON (`linktable`.`lnk_data_id` = `articles`.`art_id`)
  INNER JOIN `info` ON (`articles`.`art_info_id` = `info`.`inf_id`)
  INNER JOIN `category` ON (`articles`.`art_cat_id` = `category`.`id`)
  AND (`articles`.`art_cat_tree_id` = `category`.`fid`)
  INNER JOIN `options` ON (`articles`.`art_opt_id` = `options`.`opt_id`)
  INNER JOIN `linktags` ON (`articles`.`art_tag_set_id` = `linktags`.`lnk_tagset_id`)
  LEFT OUTER JOIN GROUP_CONCAT(`tags`) ON (`linktags`.`lnk_tag_id` = `tags`.`tag_id`)
WHERE
  `linktable`.`lnk_pgc_id` = 1

1 个答案:

答案 0 :(得分:1)

  • GROUP_CONCAT()移动到字段列表中,它不是连接条件,而是字段计算。
  • 添加GROUP BY以查找要合并的行

这给出了

SELECT 
  `articles`.`art_title`,
  `articles`.`art_bodytext`,
  `info`.`inf_start_date`,
  `info`.`inf_end_date`,
  `info`.`inf_hits`,
  `info`.`inf_acl`,
  `category`.`name`,
  `options`.`opt_tpl`,
  `options`.`opt_published`,
  `options`.`opt_options`,
  `options`.`opt_acl`,
  GROUP_CONCAT(`tags`.`tag`) AS tags
FROM
  `linktable`
  INNER JOIN `articles` ON (`linktable`.`lnk_data_id` = `articles`.`art_id`)
  INNER JOIN `info` ON (`articles`.`art_info_id` = `info`.`inf_id`)
  INNER JOIN `category` ON (`articles`.`art_cat_id` = `category`.`id`)
  AND (`articles`.`art_cat_tree_id` = `category`.`fid`)
  INNER JOIN `options` ON (`articles`.`art_opt_id` = `options`.`opt_id`)
  INNER JOIN `linktags` ON (`articles`.`art_tag_set_id` = `linktags`.`lnk_tagset_id`)
  LEFT JOIN `tags` ON (`linktags`.`lnk_tag_id` = `tags`.`tag_id`)
WHERE
  `linktable`.`lnk_pgc_id` = 1
GROUP BY `articles`.`art_id`