英文:
Why grouping method sum in slick returns Option even if column used for sum is mandatory column?
问题
创建表格 orders
(
id bigint NOT NULL,
...
created_on date NOT NULL,
quantity int NOT NULL,
...
约束 orders_pkey 主键 (id)
)
选择 DATE(o.created_on) AS date, SUM(quantity)
从 orders o
按日期分组
ordersItemsQuery.groupBy(_.createdOn).map {
case (created, group) => (created, group.map(_.quantity).sum)
}
注意 quantity 是非空列,group.map(_.quantity).sum 返回 Rep[Option[Int]] 而不是 Rep[Int],为什么?
英文:
CREATE TABLE orders
(
id bigint NOT NULL,
...
created_on date NOT NULL,
quantity int NOT NULL,
...
CONSTRAINT orders_pkey PRIMARY KEY (id)
)
SELECT DATE(o.created_on) AS date, sum(quantity)
FROM orders o
GROUP BY date
ordersItemsQuery.groupBy(_.createdOn).map{
case (created, group) => (created, group.map(_.quantity).sum)
}
notice quantity is not null column, group.map(_.quantity).sum returns Rep[Option[Int]] but not Rep[Int] why?
答案1
得分: 3
The Slick方法sum
评估Option[T]
,不应与标准的Scala集合方法sum
混淆,后者返回非可选值。
Slick的sum
是可选的,因为查询可能不会产生结果。也就是说,如果你运行SELECT SUM(column) FROM table
而没有行,你不会从数据库中得到零。相反,你得到的是没有行。Slick在这种行为上是一致的。或者更准确地说:sum
发生在数据库服务器上的SQL中,当没有行时不会产生结果。
与数据库的工作方式相反,Scala的sum
允许你对空列表进行求和(List[Int]().sum
)并得到零。
英文:
The Slick method sum
evaluates Option[T]
, and shouldn't be confused with the standard Scala collections method sum
that returns a non-optional value.
Slick's sum
is optional because a query may produce no results. That is, if you run SELECT SUM(column) FROM table
and there are no rows, you do not get back zero from the database. Instead, you get back no rows. Slick is being consistent with this behaviour. Or rather: the sum
is happening in SQL, on the database server, and doesn't produce a result when there are no rows.
In contrast to the way a database works, Scala's sum
does allow you to sum an empty list (List[Int]().sum
) and get back zero.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论