0

I want to join a N x M relation, returning all N, and a count of how many M are there:

SELECT N.*, COUNT(M.id) FROM N LEFT JOIN M ON N.id = M.n_id GROUP BY N.id

but I don't see how. Joining and aggregation seem to exclude each other, or are not implemented, or not documented (or I didn't find it).

Frischling
  • 2,100
  • 14
  • 34

1 Answers1

0

Well, I asked ChatGPT, and it gave enough hits, so that I could actually do this.

val resultSet = database.from(N)
    .leftJoin(right = M, on = N.id eq M.nId)
    .select(N.columns + count(M.id))
    .groupBy(N.id)

Referencing the count column is a bit more tricky:

val countColumn = ColumnDeclaringExpression(
     expression = count(),
     declaredName = "count",
     sqlType = IntSqlType,
     isLeafNode = false,
     extraProperties = mapOf()
   )

resultSet.map{ it[countColumn] } // for each row, this returns the count

hope it helps someone!

Frischling
  • 2,100
  • 14
  • 34