7

I'm trying to convert the following SQL query into corresponding Rust Diesel code:

SELECT COUNT(*)
FROM BookStore
WHERE BookName IN ('Lord of the Rings', 'Hobbit')
GROUP BY StoreId
HAVING COUNT(DISTINCT BookName) = 2

I was able to translate it thus far into:

let bookNames = vec!["Lord of the Rings", "Hobbit"];

let subquery = bookStores::table
.select(count_star())
.filter(bookName.eq_any(bookNames));

which I believe translates to:

SELECT COUNT(*)
FROM BookStore
WHERE BookName IN ('Lord of the Rings', 'Hobbit')

I'm having trouble finding any Diesel equivalent for the GROUP BY and the HAVING SQL clauses. Do these clauses even exist in Diesel?

rsalmei
  • 3,085
  • 1
  • 14
  • 15
user1842633
  • 305
  • 1
  • 4
  • 15
  • 2
    https://github.com/diesel-rs/diesel/issues/210 – Shepmaster Oct 21 '20 at 16:50
  • Thanks for the link. It seems like a group by clause has been added but it doesn't seem like the having clause has been implemented yet. Is this still the case or did I miss some information in the post? – user1842633 Oct 21 '20 at 16:53
  • 2
    *It seems like a group by clause has been added* — it has [not](https://docs.rs/diesel/1.4.5/diesel/associations/trait.GroupedBy.html): "This function does not generate a GROUP BY SQL statement, as it operates on data structures already loaded from the database" – Shepmaster Oct 21 '20 at 17:39
  • 2
    To just add a few words about the current state of things: * On the 1.x release series there is [this](https://github.com/diesel-rs/diesel/blob/1.4.x/diesel/src/query_dsl/group_by_dsl.rs) hidden by default (read as "not part of the supported public API") function which allows to specify group by clauses * 2.0 (the next release) will probably introduce at least some official support for group by clauses, therefore the linked issue mentions that something has been implemented * Having clauses are not supported on any version yet – weiznich Oct 22 '20 at 09:02
  • would you mind sharing `count_star()`? – hansTheFranz Dec 27 '20 at 23:24
  • did you fix this problem?@user1842633 – Dolphin Mar 27 '22 at 08:00
  • use `sql_query` https://docs.diesel.rs/diesel/fn.sql_query.html – Paul Maxwell Jul 06 '22 at 12:39

0 Answers0