一个单元格中多个值的 SQL 查询

SQL query of multiple values in one cell(一个单元格中多个值的 SQL 查询)
本文介绍了一个单元格中多个值的 SQL 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个表格(课程兴趣),其中包含一个单元格中的所有值.但这些值只是 id,我想将它们与另一个表(课程)连接起来,这样我就可以知道它们的名字.

There is a table(Course Interests) which has all the values in one cell. But those values are just ids and I want to join them with another table(Course) so I can know their names.

课程兴趣:

MemberID          MemberName              CoursesInterested
--------------    ---------------------   --------------
1                  Al                     1,4,5,6
2                  A2                     3,5,6

课程表:

CourseId          Course
--------------    ---------------------
1                 MBA 
2                 Languages
3                 English
4                 French
5                 Fashion
6                 IT

期望的输出:

MemberID          MemberName              CoursesInterested
--------------    ---------------------   --------------
1                  Al                     MBA,French,Fashion,IT
2                  A2                     English,Fashion,IT

我想在 MySql 中做一个 SQL 查询,它可以帮助我提取所需的输出.我知道如何以相反的方式进行操作(将值连接到一个单元格),但我一直在努力寻找一种方法来分离 ID 并将交叉连接到另一个表中.

I would like to do a SQL query in MySql that can help me to extract the desired output. I know how to do it in the opposite way(join values to one cell), but I've struggling on seek a way to separate the ids and do a cross-join into another table.

我将感谢社区的任何帮助.谢谢

I'll appreciate any help from the community. Thanks

推荐答案

使用 FIND_IN_SET 在逗号分隔的列表中搜索内容.

Use FIND_IN_SET to search for something in a comma-delimited list.

SELECT i.MemberID, i.MemberName, GROUP_CONCAT(c.Course) AS CoursesInterested
FROM CourseInterests AS i
JOIN Course AS c ON FIND_IN_SET(c.CourseId, i.CoursesInterested)

但是,最好创建一个关系表而不是将课程存储在单个列中.这种类型的连接无法使用索引进行优化,因此对于大表来说成本会很高.

However, it would be better to create a relation table instead of storing the courses in a single column. This type of join cannot be optimized using an index, so it will be expensive for a large table.

这篇关于一个单元格中多个值的 SQL 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)