使用 kotlin-exposed 获取最大值

Get the max value using kotlin-exposed

我想使用 kotlin 公开框架模拟此查询:

SELECT max(episodes.season_number) FROM episodes WHERE episodes.parent_id = 944947

我尝试了下一个查询:

fun countSeasonsForParentId(id: Int) = transaction {
   EpisodeTable.slice(EpisodeTable.season)
       .select { EpisodeTable.parentId eq id }
       .map { it[EpisodeTable.season] }.maxOrNull()
}

但是这个查询的结果是:

SELECT episodes.season_number FROM episodes WHERE episodes.parent_id = 944947

并在代码中选择了最大值。

如何在数据库端查找最大值并将其映射到Int

我试过类似的查询,我相信它符合您的需要。

查询是:

        Reservations
            .slice(Reservations.date.max())
            .select { Reservations.note eq "it" }
            .maxByOrNull { Reservations.date }

并生成 SQL 查询:

SELECT MAX(reservations."date") FROM reservations WHERE reservations.note = 'it'

您的查询可以用作:

    EpisodeTable
   .slice(EpisodeTable.season.max())
   .select { EpisodeTable.parentId eq id }
   .maxByOrNull { EpisodeTable.season }
   ?.get(EpisodeTable.season.max())

备选,提取一个值似乎更合适:

   EpisodeTable
   .slice(EpisodeTable.season.max())
   .select { EpisodeTable.parentId eq id }
   .firstOrNull()
   ?.get(EpisodeTable.season.max())