一个单元格中多个值的 SQL 查询 [英] SQL query of multiple values in one cell

查看:39
本文介绍了一个单元格中多个值的 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 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆