Exposed: Select a max column value in having clause

Created on 19 Feb 2018  路  3Comments  路  Source: JetBrains/Exposed

I would like to create a query that allows the equivalent SQL:
"SELECT id, foo FROM MyTable HAVING id = (SELECT MAX(id) FROM MyTable) GROUP BY id".
After diving into the source code, I can't seem to find a means to construct that type of query. Is this possible?

documentation to be documented

Most helpful comment

Perfect, on the mark. func 'wrapAsExpression' is the missing piece. Thanks!

All 3 comments

Try out:

MyTable.slice(MyTable.id, MyTable.name).
     selectAll().
     groupBy(MyTable.id).
     having {
         MyTable.id eq wrapAsExpression(MyTable.slice(MyTable.id.max()).selectAll())
     }

Perfect, on the mark. func 'wrapAsExpression' is the missing piece. Thanks!

Just for those like me who find this page via Google:

SELECT id, foo FROM MyTable HAVING id = (SELECT MAX(id) FROM MyTable) GROUP BY id. is equivalent to
SELECT id, foo FROM MyTable WHERE id = (SELECT MAX(id) FROM MyTable).

The resulting Exposed code could be simplified to this:

val alias = MyTable.alias("t0")
val subquery = alias.slice(alias[MyTable.id].max()).selectAll()

MyTable.slice(MyTable.id, MyTable.name).select { MyTable.id.eq(wrapAsExpression(subquery)) }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

brabo-hi picture brabo-hi  路  4Comments

quangIO picture quangIO  路  5Comments

gertvdijk picture gertvdijk  路  4Comments

hannesstruss picture hannesstruss  路  5Comments

fmgonsalves picture fmgonsalves  路  3Comments