我有这样的SQL查询:
SELECT parent_id, e.season_number, max_seasons.max_episode_number, b.start_year FROM episodes e
JOIN basics b USING(title_id)
JOIN (
SELECT e.season_number, max(episode_number) AS max_episode_number FROM episodes e
WHERE e.parent_id = 944947
GROUP BY e.season_number, parent_id
) AS max_seasons USING(season_number)
WHERE e.parent_id = 944947 AND e.episode_number = 1
回复如下:
parent_id|season_number|max_episode_number|start_year|
--------+-------------+------------------+----------+
944947| 1| 10| 2011|
944947| 2| 10| 2012|
944947| 3| 10| 2013|
944947| 4| 10| 2014|
944947| 5| 10| 2015|
944947| 6| 10| 2016|
944947| 7| 7| 2017|
944947| 8| 6| 2019|
我需要将其转换为使用暴露库和 Kotlin 的查询。我提取了子查询以使用别名分隔变量
subQuery
,目前我尝试这个:
val episodeMax = episode.max()
val subQuery = EpisodeTable.slice(season, episodeMax)
.select { parentId eq id }
.groupBy(parentId, season).alias("sub_query")
EpisodeTable
.join(BasicTable, JoinType.INNER,
additionalConstraint = { BasicTable.titleId eq titleId })
.join(subQuery, JoinType.INNER,
additionalConstraint = { season eq subQuery[season] })
.slice(parentId, season, subQuery[episodeMax], BasicTable.startYear)
.select { (parentId eq id) and (episode eq 1) }
.map { row ->
Season(parentId = id,
season = row[season],
totalEpisodes = row[subQuery[episodeMax]],
startYear = row[BasicTable.startYear])
}
但出现下一个错误:
java.lang.IllegalStateException:在原始表字段中找不到字段 在 org.jetbrains.expose.sql.QueryAlias.get(Alias.kt:84) ~[expose-core-0.38.2.jar:na]
因此映射结果行存在一些问题,但我不明白为什么。
我在这篇文章中遇到了与
Field not found in original table fields
类似的问题:Kotlin Exposed 中的 OrderBy SubQuery 字段
我能够通过在聚合上使用
.alias
方法来修复它。我建议你的第一行:
val episodeMax = episode.max()
至
val episodeMax = episode.max().alias("episodeMax")