How to select the all rows in a table referencing a given table, provided that at least one row matches some criteria. #2708
Answered
by
weiznich
teymour-aldridge
asked this question in
Q&A
|
Suppose I had a schema like table! {
user (id) {
id -> Int4
}
}
table! {
post (id) {
id -> Int4,
user_id -> Int4,
score -> In4
}
}I've tried something like user::table
.inner_join(post::table)
.filter(post::score.ge(50))
.load::<(User, Post)>(connection);But from a database containing: That query (as expected) returns only rather than I'd like to return all the posts belonging to a user, provided that at least one post has a score of greater than 50. I'm using Postgres as my database. |
Answered by
weiznich
Apr 9, 2021
Replies: 1 comment 1 reply
|
You need a subquery to solve this problem. Conceptually you want to write the following raw SQL query: SELECT "user"."id", "post"."id", "post"."user_id", "post"."score"
FROM "user" INNER JOIN "post" ON "post"."user_id" = "user"."id"
WHERE "post"."user_id" IN (SELECT "post"."user_id" FROM "post" WHERE "post"."score" >= 50 and )which can be literally translated into diesel's dsl as following: user::table.inner_join(post::table)
.filter(post::user_id.eq_any(post::table.select(post::user_id)filter(post::score.ge(50))))
.load<(User, Post)>(&conn)?;(Not sure if that query is actually supported or requires alias support which is not implemented yet.) |
1 reply
Answer selected by
teymour-aldridge
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need a subquery to solve this problem. Conceptually you want to write the following raw SQL query:
which can be literally translated into diesel's dsl as following:
(Not sure if that query is actually supported or requires alias support which is not implemented yet.)