question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Filtered relation count aggregate

See original GitHub issue

Problem

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:open
  • Created 2 years ago
  • Reactions:53
  • Comments:10 (1 by maintainers)

github_iconTop GitHub Comments

12reactions
TomerAberbachcommented, Dec 6, 2021

Ran into this today as well. The use case is:

  • I have “users”
  • Each user has N “classes”
  • Each class has N “submissions”
  • Each submission has a boolean “approved” field

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:

db.user.findUnique({
  where: { id: `theuserid` },
  include: {
    classes: {
      orderBy: {
        updatedAt: `desc`,
      },
      include: {
        _count: {
          select: {
            // Can't filter for unapproved submissions!
            submissions: true
          },
        },
      },
    },
  },
})

But got stuck where I have that comment.

5reactions
lskupercommented, Sep 17, 2021

That (especially filter by _count of relations) would be extremely useful. Anything new on that end?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Filter Records with Aggregate Function COUNT
It filters rows using in a condition aggregate function like COUNT. First, in SELECT, use the name of a column or columns to...
Read more >
Aggregation, grouping, and summarizing (Concepts) - Prisma
Use Prisma Client to aggregate, group by, count, and select distinct. ... To use it, you need to add the preview feature filteredRelationCount...
Read more >
How to order by filtered count on relation in prisma?
I want to list a user followers ordered to show mutual follows on top. Now I can query my table like this: followers...
Read more >
Query Expressions - Django documentation
F() is also very useful in QuerySet filters, where they make it possible to filter ... All of the aggregate functions, like Sum()...
Read more >
Aggregate awareness | Looker - Google Cloud
For example, say that you create an aggregate table for daily order counts, and the aggregate table filters for just sunglass orders coming...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found