Skip to content
Advertisement

Getting data from three tables in postgresql

I’m new to postgresql. I have three tables

Table1: teacher

tid   | t_name  | t_gender
1     | Joe     | Male
2     | Mantera | Female

Table2: school_location

school_id     | location
    1         | Location1
    2         | Location2
    3         | Location3
    4         | Location4
    5         | Location5
    6         | Location6

Table3: teachers_school_location

school_id     |  tid  |      timings
     1        |   2   | 08:00 AM - 01:00 PM
     2        |   2   | 02:00 PM - 05:00 PM
     3        |   2   | 06:00 PM - 08:00 PM
     4        |   1   | 09:00 AM - 12:00 PM
     5        |   1   | 02:00 PM - 04:00 PM

I want to write a query to get data from these three tables like this: (output in json by calling an API)

When user select tid = 1, I want output like this

Kindly look at this image

When user select tid = 2, I want output like this

Kindly look at this image

I used INNER JOINS to get an output (query is given below), but the problem is that data from teacher table is repetitive for each location.

select 
   teacher.t_name
   , teacher.t_gender
   , school_location.location
   , teachers_school_location.timings 
from teacher 
inner join teachers_school_location 
   on teacher.tid = teachers_school_location.tid 
inner join school_location 
   on school_location.school_id = teachers_school_location.school_id
where teacher.tid = 2;

Its output is:

output image of query

but I need an output like this:

desired output

How can I achieve this output?

Advertisement

Answer

as you know you can use built-in JSON functions in Postgres to prepare your JSON like so:

 SELECT
    json_build_object('t_name', t.t_name, 't_gender', t.t_gender, 'locations', locations_json)
FROM
    (
        SELECT
            tl.tid
            , json_object_agg(location, timings) locations_json
        FROM
            school_location               l
            JOIN teachers_school_location tl
                ON l.school_id = tl.school_id
        WHERE
            tl.tid = 2
        GROUP BY
            tl.tid
    )            tt
    JOIN teacher t
        ON t.tid = tt.tid;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement