我正在回答这个问题的答案: MySQL: is it possible to group_concat multiple rows?
但是我遇到了MySql错误:
#1054 - Unknown column 'CM_Cocktail.id' in 'field list'
。
当我删除此CM_Cocktail.id时,会出现下一个错误:#1054 - Unknown column 'CM_Zutat.name' in 'field list'
。我试图使用别名,但它变得更糟......也许我是盲人。
SELECT
CM_Cocktail.id, CM_Cocktail.name,
GROUP_CONCAT(CM_Zutat.name SEPARATOR ', ')
FROM (
SELECT CM_Cocktail.id, CM_Cocktail.name AS cname, CM_Zutat.name
FROM CM_Cocktail, CM_CocktailHatZutat, CM_Zutat
WHERE CM_Cocktail.id=CM_CocktailHatZutat.cocktail_id
AND CM_CocktailHatZutat.zutat_id=CM_Zutat.id
) group_attr
GROUP BY CM_Cocktail.id;

CREATE TABLE IF NOT EXISTS `CM_Cocktail` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

CREATE TABLE IF NOT EXISTS `CM_CocktailHatZutat` (
`cocktail_id` int(3) NOT NULL,
`zutat_id` int(3) NOT NULL,
`zutat_menge` int(4) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `CM_Zutat` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

答案 0 :(得分:6)
您需要在子查询中定义列别名,而不是将别名用作父字段,如下例所示:
SELECT
CocktailID, cname,
GROUP_CONCAT(ZName SEPARATOR ', ')
FROM (
SELECT CM_Cocktail.id as CocktailID, CM_Cocktail.name AS cname, CM_Zutat.name as ZName
FROM CM_Cocktail, CM_CocktailHatZutat, CM_Zutat
WHERE CM_Cocktail.id=CM_CocktailHatZutat.cocktail_id
AND CM_CocktailHatZutat.zutat_id=CM_Zutat.id
) group_attr
GROUP BY CocktailID;
答案 1 :(得分:1)
试试这个
SELECT
id, name,
GROUP_CONCAT(CM_Zutat.name SEPARATOR ', ')
FROM (
SELECT CM_Cocktail.id, CM_Cocktail.name AS cname, CM_Zutat.name
FROM CM_Cocktail, CM_CocktailHatZutat, CM_Zutat
WHERE CM_Cocktail.id=CM_CocktailHatZutat.cocktail_id
AND CM_CocktailHatZutat.zutat_id=CM_Zutat.id
) group_attr
GROUP BY id;
因为您使用子查询