I am doing SQL query using core Java on three different tables with LEFT join and getting following output:
pId pName sId sName gId gName
1 p1 11 s1 111 g1
1 p1 11 s1 112 g2
2 p2 12 s2 null null
3 p3 13 s3 113 g3
Now I want to group this as following:
[{
"pId": 1,
"pname": "p1",
"sub": [{
"sId": 11,
"sName": "s1",
"grades": [{
"gId": 111,
"gName": "g1"
}, {
"gId": 112,
"gName": "g2"
}]
}]
}, {
"pId": 2,
"pname": "p2",
"sub": [{
"sId": 12,
"sName": "s2",
"grades": []
}]
}, {
"pId": 3,
"pname": "p3",
"sub": [{
"sId": 13,
"sName": "s3",
"grades": [{
"gId": 113,
"gName": "g3"
}]
}]
}]
To group this as above mentioned output, I am doing following process in my Java code:
1) Iterate all pId
2) Iterate all sId in pId
3) Iterate all gId in sId
This takes lot of time to execute and get desired output.
Is there any way to get it done in faster way with minimum iterations?
Any help/workaround will be greatly appreciated.
I have tried hashmap over pId but still could not find a solution
order by pId, pname, sId, sNamein your SQL. Then you can build the JSON pretty easily with one pass through the data.