Skip to content

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
Discussion options

You must be logged in to vote

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.)

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@teymour-aldridge
Comment options

Answer selected by teymour-aldridge
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants