简体   繁体   English

查询多对多关系中值的总和

[英]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. 我想建立一个查询(最好在JPA / JPQL / HQL中 ,但SQL也会这样做),该查询返回所有标记,这些标记按它们引用的视频的总和排序。

For example: two videos videoA and videoB both have the tag Foo. 例如:两个视频videoA和videoB都具有标签Foo。 VideoA has 2 views, videoB has 3 views. VideoA有2个视图,videoB有3个视图。 The number to sort on for tag Foo is 5. 标签Foo上要排序的数字是5。

Here are two attempts using JPA: 这是使用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: 尝试使用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: 三个表和group by之间的简单join应该起作用:

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 看到它在这里运行: http : //sqlfiddle.com/#!9/e366a0/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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