Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Course Interests:

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

Course Table:

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

Desired Output:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
511 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...