Is Exposed 0.27.1 capable to translate the following SQL statement?
SELECT FirstName, LastName,
(SELECT COUNT(O.Id)
FROM "Order" O
WHERE O.CustomerId = C.Id) AS OrderCount
FROM Customer C;
Here is what I tried but unfortunately the subquery works independently to the rest of the query.
val query = Customer
.leftJoin(Order, { Customer.id }, { Order.customerId })
.slice(
Customer.firstName,
Customer.lastName,
intLiteral(Order
.innerJoin(Customer, { Order.customerId }, { Customer.id })
.slice(Order.id.count())
.select { Order.customerId eq Customer.id }
.first()[Order.id.count()].toInt())//.alias("OrderCount")
)
.selectAll()
Besides, if that would be possible then how I could use the alias to fetch result from the ResultRow? Following this example it seems that the solution would be to store the entire subquery with an alias()
method call in a single variable but that will look ugly. Is there any better way to do that?
Official F.A.Q. states that the only way to have subqueries is via alias for inner query:
But maybe you don't need subqueries here? This one generates a bit different SQL-query with almost same query result (in contrast with the previous one, if there were no orders for customer, it will return 0 instead of null):
Generated SQL: