scala slick left join multiple tables fetch result 作为一个序列

scala slick left join multiple tables fetch result as a sequence

我使用的是 scala 2.12.6 版和 slick 3.2.3 版

我想使用

连接 postgres 数据库中的多个表

所需的输出:

(description, product, price, Seq[Option[currencies])

我目前拥有的:

 val query = (for {
      (((description, product), price), currencies) <- ((descriptions.filter(_.language === lang.locale.toLanguageTag()) join products on (_.productId === _.id))  joinLeft prices on (_._2.id === _.priceId)) joinLeft currencies on (_._2.map(_.id) === _.priceId)
    } yield (description, product, price, currencies))

但此代码导致

(description, product, price, [Option[currencies])

有重复行

根据 SQL 兼容标准,您的 join/left-join 查询正确地产生了 (description, product, Option[price], Option[currencies])

要生成 Seq[Option[currencies]] 而不是选项 [货币],我不确定 Slick 是否可行。理论上,groupBy 应该可以,例如:

val groupQuery = joinQuery.
  groupBy{ case (dsc ,prd, prc, cur) => (dsc ,prd, prc) }.
  map{
    case ((dsc ,prd, prc), group) => (dsc ,prd, prc, group.map(_._2).someAggFunction)
  }

不幸的是,Slick 不支持 groupBy 聚合,例如 PostgreSQL 的 array_agg 或 Spark 的 collect_list。即使您有机会在 PostgreSQL 数据库上使用 slick-pg,它的 arrayAgg method doesn't work 正如我最后检查的那样。

中显示的一种解决方法是在客户端使用 Scala 的 groupBy,但它显然无法扩展。