在数据库字段中使用逗号分隔的列表是一种反模式,应不惜一切代价避免使用。
因为在SQL中将这些逗号分隔的值提取为agian是PITA。
相反,您应该添加一个单独的链接表来表示类别和电影之间的关系,如下所示:
Table categories id integer auto_increment primary key name varchar(255)Table movies id integer auto_increment primary key name varchar(255)Table movie_cat movie_id integer foreign key references movies.id cat_id integer foreign key references categories.id primary key (movie_id, cat_id)
现在你可以做
SELECt m.name as movie_title, GROUP_CONCAt(c.name) AS categories FROM movies mINNER JOIN movie_cat mc ON (mc.movie_id = m.id)INNER JOIN categories c ON (c.id = mc.cat_id)GROUP BY m.id
返回您的问题
或者可以使用数据
SELECt m.name as movie_title , CONCAt(c1.name, if(c2.name IS NULL,'',', '), ifnull(c2.name,'')) as categories FROM movies mLEFT JOIN categories c2 ON (replace(substring(substring_index(m.categories, ',', 2), length(substring_index(m.categories, ',', 2 - 1)) + 1), ',', '') = c2.id)INNER JOIN categories c1 ON (replace(substring(substring_index(m.categories, ',', 1), length(substring_index(m.categories, ',', 1 - 1)) + 1), ',', '') = c1.id)
请注意,只有每个电影有2个或更少的类别时,最后一个查询才有效。



