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.

[Subquery] Select from one table based on select (array) from another table

See original GitHub issue

Problem

In my project there’s often such a case when you need to select items from one table based on select from multiple tables (get array of ids or tags). And the select logic can be quite complicated (for instance I need to select array of tags associated with an author and based on that (those tags) select posts). I’ve read the documentation and wasn’t able to find appropriate solution. Developing those queries is quite frustrating, so it would be nice to have a typed abstraction above it. Right now I’m using the raw queries, but title aliases are not working with that (and I have to write my own alias methods to turn entity.my_property into entity.myProperty).

Suggested solution

maybe something like that

  const resultPosts = await prisma.post.findMany({
    where: {
        inArray: [
          { 
            selectFrom: [
              select: {tag},
              from: prisma.authorSubscriptions,
              where: { author: uuid }
           ];
         },
         {
            selectFrom: [
              select: {tag},
              from: prisma.postTags,
              where: { id: postId }
            ]
          }
        ]
    },
  })

Alternatives

But I don’t insist on the syntax above, probably there’re better solutions…

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:16
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

26reactions
blevinecommented, Aug 15, 2021

This is a pretty common use-case for me. Today I was Googling to try to figure out how Prisma does subselects (without using raw queries) and I was surprised to learn that it doesn’t support this yet. I’m a little concerned that you’d ask why a user couldn’t just execute multiple queries. Any use-case in which you have to execute multiple queries when you can execute a single query is obviously non-optimal. I’m sure I’m not the first person to say this, but subselects (more generically subqueries) is something that ActiveRecord has supported since forever.

1reaction
limbo-officialcommented, Apr 13, 2021
    SELECT posts.*
        FROM (
            SELECT p.*
            FROM posts p, subscriptionsByTag sbt, posttagmap ptm
            WHERE (
                ptm.tag in (
                        SELECT tag
                        FROM subscriptionsByTag
                        WHERE subscriber = $1
                    )
                AND ptm.post_id = p.id)
            ) AS posts

(^ simplified for clarity) I have three tables: one for posts, one for posttagmap (tags associated with one post) and one for subscriptions by tags (not one tag but many tags, it’s important). I need 1) get subscriptions (array of tags) by author (uuid) 2) get posts by subscriptions (array of tags, associated with one author), acquired from step 1.
Right now I can do it in two steps

             const subscriptions = await this.prisma.subscriptionsbytag.findMany({
                select: { tag: true },
                where: {
                    subscriber: {
                        equals: uuid
                    }
                }
            });
            const tags = subscriptions.map(sub => sub.tag);
            const posts = this.prisma.posts.findMany({
                where: {
                    posttagmap: {
                        some: {
                            tag: {
                                in: tags
                            }
                        }
                    }
                }
            })

But, as I know, making two queries instead of one is quite expensive, isn’t it? (although if there’s an alternative, I would be glad to find it out).

Read more comments on GitHub >

github_iconTop Results From Across the Web

SQL Subqueries - w3resource
The SQL subquery is a SELECT query that is embedded in the main SELECT statement. The subquery can be nested inside a SELECT,...
Read more >
SQL Query to Filter a Table using Another Table
In this article, we will see, how to filter a table using another table. We can perform the function by using a subquery...
Read more >
php PDO MySQL Select results of one table based on array of ...
You can accomplish this using a sub query: SELECT username FROM members WHERE username NOT IN ( SELECT blocker,blocked FROM list_blocked ...
Read more >
Examples of subselect queries - IBM
Example 1 - Select all columns and rows from the EMPLOYEE table. · Example 2 - Join the EMP_ACT and EMPLOYEE tables, select...
Read more >
How to write subqueries in SQL - SQLShack
A SQL query is a command used to request data from tables stored in relational ... how to write a subquery in SQL...
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