java - Query the sum of a value in a many-to-many relation -


my model following:

table video: int id (pk) int views  table tag: int id (pk)  table video_tag: int id (pk) int video_id (fk video.id) int tag_id (fk tag.id) 

the model describes many-to-many relationship between tags , videos. video can have multiple tags describing content. has field number of views. same tag can refer multiple videos.

i build query (preferably in jpa/jpql/hql, sql well) returns tags ordered sum of views videos refer have.

for example: 2 videos videoa , videob both have tag foo. videoa has 2 views, videob has 3 views. number sort on tag foo 5.

here 2 attempts using jpa:

@query("select t tag t, sum(v.views) viewcount video v t member of v.tags order viewcount desc") @query("select t (select t, sum(v.views) viewcount tag t, video v t member of v.tags) order viewcount desc") 

attempt using sql:

select t.id, sum(v.views) tag t, video v t.id in (select vt.tag_id video_tag vt vt.tag_id=t.id , vt.video_id=v.id) 

a simple join between 3 tables , group by should work:

select t.id, t.label, sum(views) video_tag vt inner join video v on v.id = vt.video_id inner join tag t on t.id = vt.tag_id group t.id, t.label ; 

see running here: http://sqlfiddle.com/#!9/e366a0/1


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -