I have 4 tables, as below.
Table: Class
ClassID | ClassSTD
--------------------------------
1 | STD-1
2 | STD-2
3 | STD-3
4 | STD-4
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
7 | sec-A | 3
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.
Need All Class irrespective of section or subjectAllocation Need All Section irrespective of subjectAllocation
I trying making Left JOIN, Right JOIN but not able to get desire.
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
STD-2 | | |
STD-3 | sec-A | |
STD-4 | | |
select
ClassSTD as ClassSTD,
sectionname AS SectionName,
COALESCE(GROUP_CONCAT(CASE WHEN sac.type = 'main' THEN subjectName END), '') as 'Main subjectname',
COALESCE(GROUP_CONCAT(CASE WHEN sac.type = 'optional' THEN subjectName END), '') as 'Optional subjectname'
FROM SubjectAllocationToClass sac
JOIN Class c ON c.classid = sac.classid
Left JOIN Section sc ON sc.sectionid = sac.sectionid
Left JOIN Subject sj ON sj.subjectid = sac.subjectid
GROUP BY ClassSTD, SectionName;