SQL query of multiple values in one cell

后端 未结 2 592
生来不讨喜
生来不讨喜 2020-11-27 23:21

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

相关标签:
2条回答
  • 2020-11-28 00:27

    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.

    0 讨论(0)
  • 2020-11-28 00:28

    Try this Out:

    SELECT MemberID,MemberName,Group_Concat(C.Course) from
    (
      SELECT MemberID,MemberName,SUBSTRING_INDEX(SUBSTRING_INDEX(t.CoursesInterested, ',', n.n), ',', -1) value
      FROM Table1 t CROSS JOIN 
      (
       SELECT a.N + b.N * 10 + 1 n
         FROM 
        (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
       ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
        ORDER BY n 
       ) n
     WHERE n.n <= 1 + (LENGTH(t.CoursesInterested) - LENGTH(REPLACE(t.CoursesInterested, ',', '')))
     ORDER BY MemberID,value
      ) T JOIN course C ON T.value = C.CourseId
    Group By MemberID,MemberName
    

    Fiddle Demo

    Output:


    MemberID          MemberName              CoursesInterested
    --------------    ---------------------   --------------
    1                  Al                     MBA,French,Fashion,IT
    2                  A2                     English,Fashion,IT
    
    0 讨论(0)
提交回复
热议问题