2

I have 2 simple tables in a SQLite db and a nodejs, express api endpoint that should get results by student and have the subjects as a nested array of objects.

Tables: Student(id, name) and Subject(id, name, studentId)

This is what I need to result to look like:

{
    "id": 1,
    "name": "Student name",
    "subjects": 
    [{
        "id": 1,
        "name": "Subject 1"
    },
    {
        "id": 2,
        "name": "Subject 2"
    }]
}

How can I write a query to get this result?

2 Answers 2

3

If your version of sqlite was built with support for the JSON1 extension, it's easy to generate the JSON from the query itself:

SELECT json_object('id', id, 'name', name
                 , 'subjects'
                 , (SELECT json_group_array(json_object('id', subj.id, 'name', subj.name))
                    FROM subject AS subj
                    WHERE subj.studentid = stu.id)) AS record
FROM student AS stu
WHERE id = 1;
record
---------------------------------------------------------------------------------------------------
{"id":1,"name":"Student Name","subjects":[{"id":1,"name":"Subject 1"},{"id":2,"name":"Subject 2"}]}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way to get record as pure json object not json string? I am getting response in json string
@DrashtiKheni You'd have to use your language's facilities for parsing a string holding JSON data and converting it to a native data structure.
-2

It seems that all you need is a LEFT JOIN statement:

SELECT subject.id, subject.name, student.id, student.name 
FROM subject 
LEFT JOIN student ON subject.studentId = student.id
ORDER BY student.id;

Then just parse the rows of the response into the object structure you require.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.