简体   繁体   中英

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

My model is the following:

table video:
int id (PK)
int views

table tag:
int id (PK)

table video_tag:
int id (PK)
int video_id (FK to video.id)
int tag_id (FK to tag.id)

The model describes a many-to-many relationship between tags and videos. A video can have multiple tags describing its content. It also has a field with the number of views. The same tag can also refer to multiple videos.

I would like to build a query (preferably in JPA/JPQL/HQL , but SQL will do as well) that returns all the tags ordered by the sum of the views the videos they refer to have.

For example: two videos videoA and videoB both have the tag Foo. VideoA has 2 views, videoB has 3 views. The number to sort on for tag Foo is 5.

Here are two attempts using JPA:

@Query("SELECT t FROM Tag t, SUM(v.views) as viewCount FROM Video v WHERE t MEMBER OF v.tags ORDER BY viewCount DESC")
@Query("SELECT t FROM (SELECT t, SUM(v.views) as viewCount FROM Tag t, Video v WHERE t MEMBER OF v.tags) ORDER BY viewCount DESC")

Attempt using SQL:

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

A simple join between the three tables and a group by should work:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM