【问题标题】:Query the sum of a value in a many-to-many relation查询多对多关系中某个值的总和
【发布时间】:2016-01-27 20:23:03
【问题描述】:

我的模型如下:

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)

【问题讨论】:

  • DownVoted 因为它根本没有表现出任何努力。只是要求。
  • 我添加了两次尝试将查询限制为 JPA

标签: java mysql sql database jpa


【解决方案1】:

三个表之间的简单joingroup by 应该可以工作:

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

【讨论】:

  • 我还发现了做同样事情的 JPA 查询(甚至更短:)) SELECT t FROM Tag t JOIN FETCH t.videos v GROUP BY t ORDER BY SUM(v.views) DESC跨度>
猜你喜欢
  • 2021-08-07
  • 2014-10-09
  • 2011-06-06
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多