簡體   English   中英

查詢多對多關系中值的總和

[英]Query the sum of a value in a many-to-many relation

我的模型如下:

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)

該模型描述了標簽和視頻之間的多對多關系。 一個視頻可以有多個描述其內容的標簽。 它還具有一個包含視圖數的字段。 同一標簽也可以引用多個視頻。

我想建立一個查詢(最好在JPA / JPQL / HQL中 ,但SQL也會這樣做),該查詢返回所有標記,這些標記按它們引用的視頻的總和排序。

例如:兩個視頻videoA和videoB都具有標簽Foo。 VideoA有2個視圖,videoB有3個視圖。 標簽Foo上要排序的數字是5。

這是使用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")

嘗試使用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)

三個表和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
;

看到它在這里運行: http : //sqlfiddle.com/#!9/e366a0/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM