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

时间:2014-06-16 10:48:26

标签: mysql sql

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

课程兴趣:

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并将交叉连接转换为另一个表。

我会感谢社区的任何帮助。感谢

2 个答案:

答案 0 :(得分:5)

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

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)

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

答案 1 :(得分:2)

试试这个:

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

输出:


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