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
相关产品推荐
相关产品推荐

