如何在MySQL中使用GROUP_CONCAT功能而不使用GROUP BY?

时间:2013-04-16 00:03:00

标签: mysql sql concatenation group-concat

这是检索课程数据的原始SQL语句:

SELECT
    `courses`.`id` AS `id`,
    `courses`.`title` AS `title`,
    `courses`.`description` AS `description`,
    MATCH (coursedata.title) AGAINST ('Salsa') * 5 + MATCH (coursedata.description) AGAINST ('Salsa') * 2 AS `relevance`,
    GROUP_CONCAT(trainers.name SEPARATOR '|||') AS `trainers`
FROM `courses`
INNER JOIN `coursedata` ON `courses`.`id` = `coursedata`.`id`
        INNER JOIN `courses_trainers` ON `courses`.`id` = `courses_trainers`.`course_id`
INNER JOIN `trainers` ON `trainer_id` = `trainers`.`id`
GROUP BY `courses`.`id`
HAVING `relevance` >= '3'

由于它使用MySQL Extensions to GROUP BY并且无法执行,如果sql_mode设置为ONLY_FULL_GROUP_BY,我必须使其符合标准SQL:

SELECT * FROM (
    SELECT
        `courses`.`id` AS `id`,
        `courses`.`title` AS `title`,
        `courses`.`description` AS `description`,
        MATCH (coursedata.title) AGAINST ('Salsa') * 5 + MATCH (coursedata.description) AGAINST ('Salsa') * 2 AS `relevance`
        -- , GROUP_CONCAT(trainers.name SEPARATOR '|||') AS `trainers`
    FROM `courses`
    INNER JOIN `coursedata` ON `courses`.`id` = `coursedata`.`id`
    LEFT JOIN `courses_trainers` ON `courses`.`id` = `courses_trainers`.`course_id`
    LEFT JOIN `trainers` ON `trainer_id` = `trainers`.`id`
) AS subselect
WHERE `relevance` >= '3'

这个很好,但我不能再使用GROUP_CONCAT函数(为了将多个trainer字段连接到一个字段/字符串)。

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP_CONCAT(trainers.name SEPARATOR '|||') AS `trainers`
    FROM `courses`
    INNER' at line 7

是否有其他方法可以使用GROUP_CONCAT功能?

0 个答案:

没有答案