Filtered relation count aggregate
See original GitHub issueProblem
Briefly discussed here: https://github.com/prisma/prisma/discussions/6554.
I would like to execute a query where it would be possible for me to include an additional (named?) column (similar to _count
) which value would aggregate relation information based on a provided filter. In my problem, I am referring to count but possibly you could broaden it to more aggregates.
Example Query I would like to see movie’s watchers (count) but only from today or fulfilling another requirement (where) all in the same query returning list of movies (filtered in it’s own way) to maintain pagination on the database level.
Suggested solution
Using SQL as a reference I was thinking about something like (example of Movie-Watchers one-to-many relation, where each watcher has seen the movie on a particular date which will be compared against our filter):
SELECT movie_id,
movie_name,
...other_movie_columns,
watchers_day_count
FROM movies m
JOIN
(SELECT count(*) AS watchers_day_count,
w.movie_id
FROM watchers w
WHERE w.watched_date = '<our-filter>`
GROUP BY w.movie_id,
w.watched_date) daily_watchers
ON m.movie_id = daily_watchers.movie_id
WHERE ...main_query_filters
In general, I am thinking about making an extra join with a grouped subquery.
Alternatives
As for now, I was thinking only about the above solution with extra relation join because the solution involves custom grouping and where filter.
Additional context
It would be really helpful if you could also sort using this extra filtered count column. In my scenario, I have a query that is listing movies with the total number of watchers (_count
) and I would like to add an extra column for a number of watchers who have seen it on a specific date (or between date range). In my situation, I have all generic implementation which adds pagination on top of findMny
that’s why it is important for me to limit this to a single query.
Feture reuqeust is db agnostic but personally I come from MySQL with this.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:53
- Comments:10 (1 by maintainers)
Top GitHub Comments
Ran into this today as well. The use case is:
I would like to be able to query the user’s classes and for each class how many unapproved submissions it has. I ended up with this:
But got stuck where I have that comment.
That (especially filter by _count of relations) would be extremely useful. Anything new on that end?