栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在联接字段中使用逗号分隔列表联接两个表

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在联接字段中使用逗号分隔列表联接两个表

在数据库字段中使用逗号分隔的列表是一种反模式,应不惜一切代价避免使用。
因为在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个或更少的类别时,最后一个查询才有效。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421218.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号