0
SELECT s.subject_id
     , s.subject_name
     , t.class_id
     , t.section_id
     , c.teacher_id
  FROM school_timetable_content c
  JOIN s  
    ON c.subject_id = s.subject_id
  JOIN school_timetables t 
    ON t.timetable_id = c.timetable_id
 WHERE c.teacher_id = 184
   AND t.class_id = 24
   AND t.school_id = 28

From the above query, I get the following result shown below:-

Result for the above query

again from the above result I want to get subjects which are associated with all the unique section_id 15, 16,26. i.e Expected output Hindi,Maths

Strawberry
  • 33,750
  • 13
  • 40
  • 57
Student
  • 25
  • 2
  • 11
  • Welcome to SO. Please see [Why should I provide an MCRE for what seems to me to be a very simple SQL query](http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query) – Strawberry Jun 06 '20 at 11:07
  • 1
    This question is quite clear. I have no idea why someone would close it. – Gordon Linoff Jun 06 '20 at 11:17
  • @GordonLinoff no MCRE and an image – nbk Jun 06 '20 at 11:27

1 Answers1

1

The idea is to filter for exactly those three sections. Then aggregate and count if all three are present:

SELECT s.subject_id, s.subject_name
FROM school_timetable_content tc JOIN
     school_subjects s
     ON tc.subject_id = s.subject_id JOIN
     school_timetables t
     ON t.timetable_id = tc.timetable_id
WHERE tc.teacher_id = 184 AND 
      t.class_id = 24 AND
      t.school_id = 28 AND
      t.section_id IN (15, 16, 26)
GROUP BY s.subject_id, s.subject_name
HAVING COUNT(*) = 3;

This assumes that section_id is not duplicated. If that is possible, use HAVING(COUNT(DISTINCT section_id)) = 3 instead.

Note that the use of table aliases makes the query easier to write and to read.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786