Search code examples
mysqlsqlselectgroup-bygroup-concat

MYSQL comma base separated select result


I have 4 tables, as below.

Table: Class

ClassID     |   ClassSTD
--------------------------------
1           |   STD-1<br>
2           |   STD-2

Table: Section

SectionId   |   SectionName | ClassId
--------------------------------------------
1           |   sec-A       | 1
2           |   sec-B       | 1
3           |   sec-C       | 1
4           |   sec-A       | 2
5           |   sec-B       | 2
6           |   sec-C       | 2

Table: Subject

subjectId   |   subjectName
------------------------------------
1           |   Art
2           |   Music
3           |   Play

Table SubjectAllocationToClass

    classId         |   sectionID           |   subjectId   | type
-----------------------------------------------------------------------
1(STD-1)        |   1(sec-A)            |   1(Art)      | main
1(STD-1)        |   2(sec-B)            |   1(Art)      | main
1(STD-1)        |   3(sec-C)            |   1(Art)      | optional
1(STD-1)        |   1(sec-A)            |   2(Music)    | main
1(STD-1)        |   2(sec-B)            |   2(Music)    | optional

Above table "SubjectAllocationToClass" shows distribution of two type of subject (Main and optional) to section for class. How I can achieve below result from SELECT statement?

classSTD |  sectionName | Main subjectName   | Optional subjectName
-----------------------------------------------------------------------------
STD-1    |  sec-A       | Art, Music         |
STD-1    |  sec-B       | Art                |  Music
STD-1    |  sec-C       |                    |  Art

Solution

  • Use GROUP_CONCAT() function:

    Try this:

    SELECT D.classSTD, 
           C.sectionName, 
           GROUP_CONCAT(B.subjectName SEPARATOR ', ') AS subjectName
    FROM SubjectAllocationToClass A 
    INNER JOIN Subject B ON A.subjectId = B.SubjectId 
    INNER JOIN Section C ON A.sectionId = C.SectionId   
    INNER JOIN Class D ON A.classID = D.ClassID 
    GROUP BY D.ClassID, C.SectionId;
    

    For your another question

    SELECT D.classSTD, 
           C.sectionName, 
           GROUP_CONCAT(B.subjectName SEPARATOR ', ') AS subjectName, 
           GROUP_CONCAT(CASE WHEN B.type = 'main' THEN B.subjectName ELSE NULL END SEPARATOR ', ') AS mainsubjectName, 
           GROUP_CONCAT(CASE WHEN B.type = 'optional' THEN B.subjectName ELSE NULL END SEPARATOR ', ') AS optionalSubjectName
    FROM SubjectAllocationToClass A 
    INNER JOIN SUBJECT B ON A.subjectId = B.SubjectId 
    INNER JOIN Section C ON A.sectionId = C.SectionId   
    INNER JOIN Class D ON A.classID = D.ClassID 
    GROUP BY D.ClassID, C.SectionId;