【发布时间】:2019-07-04 02:27:49
【问题描述】:
有一些表:
case class Thing(name: String, color: Option[String], height: Option[String])
class ThingSchema(t: Tag) extends Table[Thing](t, "things") {
def name = column[String]("name")
def color = column[Option[String]]("color")
def height = column[Option[String]]("height")
def * = (name, color, height) <> (Thing.tupled, Thing.unapply)
}
val things = TableQuery[ThingSchema]
例如things表中有如下数据:
| name | color | height |
+---------+-----------+--------+
| n1 | green | <null> |
| n1 | green | <null> |
| n1 | <null> | normal |
| n1 | <null> | normal |
| n1 | red | <null> |
| n2 | red | <null> |
我需要从以上数据中得到如下结果:
| name | color | height | size |
+---------+-----------+--------+------+
| n1 | green | <null> | 2 |
| n1 | <null> | normal | 2 |
| n1 | red | <null> | 1 |
| n2 | red | <null> | 1 |
为了解决这个任务,我使用了以下分组查询:
SELECT name, color, null, count(*) AS size
FROM things
GROUP BY name, color
UNION ALL
SELECT name, null, height, count(*) AS size
FROM things
GROUP BY name, height
我尝试使用 Slick 创建此查询:
val query1 =
things.groupBy(t => (t.name, t.color))
.map { case ((name, color), g) => (name,color,None, g.size)} //Error#1
val query2 =
things.groupBy(t => (t.name, t.height))
.map { case ((name, height), g) => (name,None,height,g.size)} //Error#1
val query = query1 ++ query2
但上面的代码没有被编译,因为 Slick 不能为 None 值定义 ConstColumn 的类型(参见上面代码中的 //Error#1 注释)。
这适用于 NOT-null 值(例如 numbers、strings),但不适用于表示为 Option[String]=None 的 Nullable 值。
在这种情况下,如何将ConstColumn 用于None 值?
【问题讨论】: