Skip to content

Combine multiple queries into single SELECT query #2644

@tqwewe

Description

@tqwewe

Setup

Versions

  • Rust: 1.23.1
  • Diesel: 1.4.4
  • Database: Postgres
  • Operating System MacOS

Feature Flags

  • diesel: ["postgres", "r2d2"]

Problem Description

Given the following SQL query:

SELECT * FROM
        /* Has previous page */
        (SELECT COUNT(*) > 0 as has_previous_page
            FROM reviews
            WHERE store_id = $1 AND id < $2) as has_previous_page,

        /* Has next page */
        (SELECT COUNT(*) > 0 as has_next_page
            FROM reviews
            WHERE store_id = $1 AND id > ($3 + 1)) as has_next_page,

        /* Total count */
        (SELECT COUNT(*) as total_count
            FROM reviews
            WHERE store_id = $1) as total_count

How can I execute this in Diesel?

So far I have:

let has_previous_page_query = reviews
        .select(count_star().gt(0))
        .filter(store_id.eq(store_id_param))
        .filter(id.lt(after))
        .single_value();

let has_next_page_query = reviews
        .select(count_star().gt(0))
        .filter(store_id.eq(store_id_param))
        .filter(id.gt(after + first))
        .single_value();

let total_count_query = reviews
        .count()
        .filter(store_id.eq(store_id_param))
        .single_value();

// Need to combine the three queries with `SELECT * FROM query1, query2, query3` in diesel

I am not sure how I can run a select query on all three of these queries in a single query. Is this functionality missing from Diesel? Or is it something I am missing?

Checklist

  • This issue can be reproduced on Rust's stable channel. (Your issue will be
    closed if this is not the case)
  • This issue can be reproduced without requiring a third party crate

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions