本文介绍了如何使用 slick 进行聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想强制 slick 创建像
I want to force slick to create queries like
select max(price) from coffees where ...
但是 slick 的文档没有帮助
val q = Coffees.map(_.price) //this is query Query[Coffees.type, ...]
val q1 = q.min // this is Column[Option[Double]]
val q2 = q.max
val q3 = q.sum
val q4 = q.avg
因为那些 q1-q4 不是查询,我无法获得结果,但可以在其他查询中使用它们.
Because those q1-q4 aren't queries, I can't get the results but can use them inside other queries.
本声明
for {
coffee <- Coffees
} yield coffee.price.max
生成正确的查询但已被弃用(生成警告:不推荐使用类 ColumnExtensionMethods 中的方法 max:改为使用 Query.max").如何在没有警告的情况下生成这样的查询?
generates right query but is deprecated (generates warning: " method max in class ColumnExtensionMethods is deprecated: Use Query.max instead").How to generate such query without warnings?
另一个问题是与 group by 聚合:
Another issue is to aggregate with group by:
"select name, max(price) from coffees group by name"
试图解决它
for {
coffee <- Coffees
} yield (coffee.name, coffee.price.max)).groupBy(x => x._1)
产生
select x2.x3, x2.x3, x2.x4 from (select x5."COF_NAME" as x3, max(x5."PRICE") as x4 from "coffees" x5) x2 group by x2.x3
导致明显的数据库错误
column "x5.COF_NAME" must appear in the GROUP BY clause or be used in an aggregate function
如何生成这样的查询?
推荐答案
据我所知是第一个简单
Query(Coffees.map(_.price).max).first
第二个
val maxQuery = Coffees
.groupBy { _.name }
.map { case (name, c) =>
name -> c.map(_.price).max
}
maxQuery.list
或
val maxQuery = for {
(name, c) <- Coffees groupBy (_.name)
} yield name -> c.map(_.price).max
maxQuery.list
这篇关于如何使用 slick 进行聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!