You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Exposed SQL多外键关联查询:如何获取三个关联车站名称

解决Exposed多外键关联同一张表获取对应车站名称的问题

你之前的查询报错,核心原因是一次关联无法同时匹配三个外键,而且Exposed不允许未加别名的情况下多次关联同一张表(字段会冲突)。要获取当前站、起点站、终点站三个名称,需要给Stations表创建三个别名,分别关联Train表的三个外键字段。

正确实现代码

db.dbQuery {
    // 给Stations表创建三个别名,区分不同关联场景
    val currentStation = Stations.alias("current_station")
    val srcStation = Stations.alias("src_station")
    val destStation = Stations.alias("dest_station")

    // 依次关联三个别名表,每个关联对应Train的一个外键
    (Train innerJoin currentStation on (Train.cStnCode eq currentStation[Stations.code]))
        .innerJoin(srcStation on (Train.srcCode eq srcStation[Stations.code]))
        .innerJoin(destStation on (Train.destCode eq destStation[Stations.code]))
        .selectAll()
        .map { row ->
            TrainClass(
                no = row[Train.numb],
                na = row[Train.name],
                cStC = row[Train.cStnCode],
                // 从对应别名表中取车站名称
                cStN = row[currentStation[Stations.name]],
                dly = row[Train.delay],
                sC = row[Train.srcCode],
                sN = row[srcStation[Stations.name]],
                dC = row[Train.destCode],
                dN = row[destStation[Stations.name]]
            )
        }
}

补充说明

  • 如果存在外键字段可能为null的场景(比如列车尚未出发,当前站为空),可以把innerJoin换成leftJoin,避免丢失数据。
  • 别名的命名可以根据业务场景自定义,只要能清晰区分不同关联即可。

内容的提问来源于stack exchange,提问作者Pawandeep Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 04:07:16