Search code examples
sqldatabaseone-to-many

One to many "twice" in one sql query (or in an efficient way)


I have teachers, classes and students. My table classes have a foreign key to a teacher and students have a foreign key to a class (a teacher has many classes, and each class has many students). My goal is to get all classes and all students from one teacher, returning a json like this:

[
 {
  "class_id":1,
  "name":"Class One",
  "students":[
   {
    "student_id":1,
    "name":"Student One"
   },
   {
    "student_id":2,
    "name":"Student Two"
   }
  ]
 },
 {
  "class_id":2,
  "name":"Class Two",
  "students":[
   {
    "student_id":3,
    "name":"Student Three"
   },
   {
    "student_id":4,
    "name":"Student Four"
   }
  ]
 }
]

The only thought that pass through my mind is to make one query to get all classes from a teacher and with this result iterate in classes and make a query for each one to get its students (but this sounds very inefficient).

What alternatives do I have?


Solution

  • Just join the 3 tables together in a single SQL query