假设我在Slick 3.2.3中定义了一个这样的表:
class ATable(tag: Tag) extends Table[(Int, Option[Boolean])](tag, "a_table") {
def someInt = column[Int]("some_int")
def someBool = column[Option[Boolean]]("some_bool")
def * = (someInt, someBool)
}
object ATable extends TableQuery(new ATable(_))
以及一些数据:
insert into a_table
values
(1, true),
(2, null),
(2, true),
(2, null),
(3, true),
(3, true),
(3, null);
现在,我想在表中找到那些整整一行的地方,其中some_bool
不是null
。在SQL中这并不困难:
select some_int
from a_table
group by some_int
having count(some_bool) = 1;
这很好用。因此,让我们尝试使用Slick:
ATable
.groupBy(_.someInt)
.filter(_._2.map(_.someBool).countDefined === 1)
.map(_._1)
并且在编译时,它将在运行时崩溃,并显示错误消息“ slick.SlickTreeException: Cannot convert node to SQL Comprehension
”。这是已知的限制还是光滑的错误?还是我应该以其他方式编写查询?
当然可以用子查询来编写它,但是我宁愿理解为什么groupBy
这件事不起作用…
答案 0 :(得分:1)
在以下示例中,SQL的Slick
等效应类似于query
:
val aTable: TableQuery[ATable] = TableQuery[ATable]
val setupAction: DBIO[Unit] = DBIO.seq(
aTable.schema.create,
aTable += (1, Some(true)),
aTable += (2, None),
aTable += (2, Some(true)),
aTable += (2, None),
aTable += (3, Some(true)),
aTable += (3, Some(true)),
aTable += (3, None)
)
val setupFuture: Future[Unit] = db.run(setupAction)
val f = setupFuture.flatMap{ _ =>
val query =
aTable.groupBy(_.someInt).
map{ case (someInt, group) => (someInt, group.map(_.someBool).countDefined) }.
filter(_._2 === 1).
map(_._1)
println("Generated SQL for query:\n" + query.result.statements)
db.run(query.result.map(println))
}
// Generated SQL for query:
// List(select "some_int" from "a_table" group by "some_int" having count("some_bool") = 1)
// Vector(1, 2)