-
I have a sqlite database with 2 tables
and
Books have no default status, books.status_id is -1. SELECT * FROM books LEFT JOIN statuses USING (status_id) ORDER BY IFNULL(statuses.priority, 100) DESC
Is it possible to do the same with diesel? diesel code: let mut query = books::table
.left_join(statuses::table)
.select((Book::as_select(), Option::<Status>::as_select())).into_boxed();
// some filtering in between
// how do I set a default value for null priority
query = query.order_by(statuses::priority.desc());
let results = query.load::<(Book, Option<Status>)>(connection)
.expect("Error loading book"); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There are several answers to the question depending on the database system you are using and how you want to solve the actual problem. For postgres diesel offers functions for the Other backends do not support the same syntax, but you can solve this by using Finally it's always possible to use |
Beta Was this translation helpful? Give feedback.
There are several answers to the question depending on the database system you are using and how you want to solve the actual problem.
For postgres diesel offers functions for the
NULLS FIRST/LAST
sorting options: https://docs.diesel.rs/2.2.x/diesel/expression_methods/trait.PgSortExpressionMethods.html#method.nulls_last. That would neatly solve your problem.Other backends do not support the same syntax, but you can solve this by using
ifnull
orcoalesce
as you already mentioned.Diesel does not provide out of the box support for these functions, but you can easily define your own version of them via the
define_sql_function!
macro. After that you can just use these functions in your order…