我想在 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"