Oskar Persson
Oskar Persson

Reputation: 6753

How do I get the row with minimum value in a column using Diesel?

How do I get the row with the minimum value using the Diesel ORM? I want it to generate a query looking like this

SELECT tbl.*
FROM TableName tbl
  INNER JOIN
  (
    SELECT Id, MIN(Point) MinPoint
    FROM TableName
    GROUP BY Id
  ) tbl1
  ON tbl1.id = tbl.id
WHERE tbl1.MinPoint = tbl.Point

Upvotes: 0

Views: 389

Answers (1)

weiznich
weiznich

Reputation: 3435

Without extending the dsl provided by diesel it is only possible to express this query via sql_query.

Applied to this example this leads to the following query:

sql_query("
SELECT tbl.*
FROM TableName tbl
  INNER JOIN
  (
    SELECT Id, MIN(Point) MinPoint
    FROM TableName
    GROUP BY Id
  ) tbl1
  ON tbl1.id = tbl.id
WHERE tbl1.MinPoint = tbl.Point
").load::<ResultType>(&conn)?

where ResultType is a type that implements QueryableByName

Upvotes: 1

Related Questions