带分组查询的scala光滑联接表

laik7k3q  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(322)

我有两张table:
商店
类shoptable(tag:tag)扩展了generictableshop,uuid{

def * = (id.?, name, address) <> (Shop.tupled, Shop.unapply _)

 def name = column[String]("name")

 def address = column[String]("address")

}
val shoptable=tablequery[shopdao.shoptable]
秩序
类ordertable(tag:tag)扩展了generictableorder,uuid{

def * = (id.?, shopId, amount) <> (Order.tupled, Order.unapply _)

 def shopId = column[UUID]("shop_id")

 def amount = column[Double]("amount")

}
val ordertable=表格查询[orderdao.ordertable]
我可以得到商店的静态(订单数量,订单金额总和):

def getStatisticForShops(shopIds: List[UUID]): Future[Seq(UUID, Int, Double)] = {
  searchStatisticsByShopIds(shopIds).map(orderStatistics => 
    shopIds.map(shopId => {
      val o = orderStatistics.find(_._1 == shopId)
      (
        shopId,
        o.map(_._2).getOrElse(0),
        o.map(_._3).getOrElse(0.0)
      )
    })
  )
}

 def searchStatisticsByShopIds(shopIds: List[UUID]): Future[Seq(UUID, Int, Double)] = 
  db.run(searchStatisticsByShopIdsCompiled(shopIds).result)

 private val searchStatisticsByShopIdsCompiled = Compiled((shopIds: Rep[List[(UUID)]]) =>
  orderTable.filter(_.shopId === shopIds.any)
    .groupBy(_.shopId)
    .map { case (shopId, row) =>
      (shopId, row.length, row.map(_.amount).sum.get)
    }
 )

我需要排序和过滤购物表的订单计数。
如何将分组的ordertable连接到shoptable,并为缺失的商店设置零值?
我想有这样一个要求:

| id(shopId) | name | address | ordersCount | ordersAmount |
|     id1    | name | address |       4     |    200.0     |
|     id2    | name | address |       0     |     0.0      |
|     id3    | name | address |       2     |    300.0     |

我使用scala 2.12.6,slick 2.12:3.0.1,play slick 3.0.1,slick pg 0.16.3
p、 我可能已经找到了解决办法

val shopsOrdersQuery: Query[(Rep[UUID], Rep[Int], Rep[Double]), (UUID, Int, Double), Seq] = searchShopsOrdersCompiled.extract

// Query shops with orders for sorting and filtering
val allShopsOrdersQueryQuery = shopTable.joinLeft(shopsOrdersQuery).on(_.id === _._1)
  .map(s => (s._1, s._2.map(_._2).getOrElse(0), s._2.map(_._3).getOrElse(0.0)))

private val searchShopsOrdersCompiled = Compiled(
  orderTable.groupBy(_.shopId)
    .map { case (shopId, row) =>
      (shopId, row.length, row.map(_.amount).sum.get)
    }
)
rkttyhzu

rkttyhzu1#

是的,这个解决方案很好用

val shopsOrdersQuery: Query[(Rep[UUID], Rep[Int], Rep[Double]), (UUID, Int, Double), Seq] = searchShopsOrdersCompiled.extract

// Query shops with orders for sorting and filtering
val allShopsOrdersQueryQuery = shopTable.joinLeft(shopsOrdersQuery).on(_.id === _._1)
  .map(s => (s._1, s._2.map(_._2).getOrElse(0), s._2.map(_._3).getOrElse(0.0)))

private val searchShopsOrdersCompiled = Compiled(
  orderTable.groupBy(_.shopId)
    .map { case (shopId, row) =>
      (shopId, row.length, row.map(_.amount).sum.get)
    }
)

相关问题