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

How to query an optional column value with a fallback in Slick 3.x

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

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

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"