如何在 Slick 3.x 中使用回退查询可选列值

  • 本文关键字:查询 回退 Slick scala slick
  • 更新时间 :
  • 英文 :


我想在 Slick 中编写一个查询,如果它不为 null,则获取一列,如果它为 null,则默认为另一列的值。如何在不重复调用 db.run 的情况下做到这一点?

假设您的表定义如下所示:

import slick.driver.PostgresDriver.api._ // Import your driver here
class EmployeesTable(tag: Tag) extends Table[(Option[Int], Int)](tag, "employees") {
  def firstCol = column[Option[Int]]("first_col") // This column is nullable
  def secondCol = column[Int]("second_col") // This column is non-nullable
  def * = (firstCol, secondCol)
}

然后,您的查询可能如下所示:

val query = TableQuery[EmployeesTable].map(employee => employee.firstCol.ifNull(employee.secondCol))
val result: Future[Seq[Int]] = db.run(query.result)

这样,first_col中的每个空值都将替换为 second_col 中的值。这将等效于以下 SQL 查询:

select coalesce("first_col", "second_col") from "employees"

最新更新