postgresql - Limit query by count distinct column values -
i have table people, this:
id personid someattribute 1 1 yellow 2 1 red 3 2 yellow 4 3 green 5 3 black 6 3 purple 7 4 white
previously returning of persons api seperate objects. if user set limit 3, setting query maxresults in hibernate 3 , returning:
{"personid": 1, "attr":"yellow"} {"personid": 1, "attr":"red"} {"personid": 2, "attr":"yellow"}
and if specify limit 3 , page 2(setmaxresult(3), setfirstresult(6) be:
{"personid": 3, "attr":"green"} {"personid": 3, "attr":"black"} {"personid": 3, "attr":"purple"}
but want select people , combine 1 json object this:
{ "personid":3, "attrs": [ {"attr":"green"}, {"attr":"black"}, {"attr":"purple"} ] }
and here problem. there possibility in postgresql or hibernate set limit not number of rows number of distinct people ids, because if user specifies limit 4 should return person1, 2, 3 , 4, in current limiting mechanism return person1 2 attributes, person2 , person3 1 attribute. same problem pagination, can return half of person3 array attrs on 1 page , half on next page.
i'm assuming have person
table. jpa, should query on person
table(one side), not on personcolor
(many side).then limit applied on number of rows of person
then
if don't have person table , can't modify db, can use sql , group personid
, , concatenate colors
select personid, array_agg(color) my_table group personid limit 2
Comments
Post a Comment