我想在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)
}
Run Code Online (Sandbox Code Playgroud)
然后您的查询可能如下所示:
val query = TableQuery[EmployeesTable].map(employee => employee.firstCol.ifNull(employee.secondCol))
val result: Future[Seq[Int]] = db.run(query.result)
Run Code Online (Sandbox Code Playgroud)
这样,每个空值都first_col将被一个值替换second_col.这将等同于以下SQL查询:
select coalesce("first_col", "second_col") from "employees"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1164 次 |
| 最近记录: |