JPQL:SELECT b, count(ts) FROM Branch b JOIN b.tourScheduleList WHERE ts.deleted = 0

JPQL: SELECT b, count(ts) FROM Branch b JOIN b.tourScheduleList WHERE ts.deleted = 0

我在这里得到了想要的结果

SELECT b, count(ts) FROM Branch b JOIN b.tourScheduleList ts WHERE ts.deleted =  0 GROUP BY b.id ORDER BY b.name ASC

b1 | 2
b2 | 1

但随后我需要获取 ts.tourAppliedList 的计数,因此我将查询更新为

SELECT b, count(ts), count(ta) FROM Branch b JOIN b.tourScheduleList ts JOIN ts.tourAppliedList ta WHERE ts.deleted =  0 GROUP BY b.id ORDER BY b.name ASC

这导致

b1 | 3 | 3
b2 | 2 | 2

结果是错误的。我不知道为什么 count(ts) 等于 count(ta)

我尝试返回 ts 然后稍后再做一个计数,但它返回所有内容而不考虑 ts.deleted = 0

SELECT b, ts FROM Branch b JOIN b.tourScheduleList ts WHERE ts.deleted =  0 GROUP BY b.id ORDER BY b.name ASC

然后在视图中我只是 #{item.ts.tourAppliedList.size()} 它没有考虑 ts.deleted = 0

问题是你的期望是错误的。 此加入将为您提供:

b1 | ts1 | ta1
b1 | ts1 | ta2
b1 | ts2 | ta3
b2 | ts3 | ta4
b2 | ts3 | ta5

或者沿着这条线... 当您对这些行进行分组和计数时会发生什么? 很简单,b1 有 3 个条目,b2 有 2 个条目。 你需要的是 count(distinct ts) 由于每个不同的 ta 都有多个 ts,因此您会发现差异

P.s。我不知道 jpql 是否允许计数(distinct),如果是这样的话,你最好做两个查询并计算 ts 仅在 ts 上连接,然后 ta 连接在 ts 和 ta