Why grouping method sum in slick returns Option even if column used for sum is mandatory column?

huangapple go评论116阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年1月6日 21:17:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定