gpt4 book ai didi

scala - 在 slick 中更新表的前 n 行

转载 作者:行者123 更新时间:2023-12-05 05:22:08 26 4
gpt4 key购买 nike

我想在使用 slick 3.0 时更新表格的前 n 行而不是整个表格

这是更新所有版本:

private[this] val active = this.filter(a => a.status =!= AccountStatus.DISABLED)
db.run(
active.filter(a => a.usedBy.isEmpty || a.usedBy === Host.name)
.map(account => account.usedBy)
.update("host-a")
)

我尝试使用这个版本,但它不起作用并抛出异常

private[this] val active = this.filter(a => a.status =!= AccountStatus.DISABLED)
db.run(
active.filter(a => a.usedBy.isEmpty || a.usedBy === Host.name)
.take(10)
.map(account => account.usedBy)
.update(Option(Host.name))
)

异常

Caused by: slick.SlickException: A query for an UPDATE statement must resolve to a comprehension with a single table -- Unsupported shape: Comprehension s2, Some(Apply Function and), None, ConstArray(), None, None, Some(LiteralNode 100 (volatileHint=false)), None
at slick.driver.JdbcStatementBuilderComponent$QueryBuilder.buildUpdate(JdbcStatementBuilderComponent.scala:447)
at slick.driver.JdbcProfile$$anonfun$updateCompiler$1.apply(JdbcProfile.scala:30)
at slick.driver.JdbcProfile$$anonfun$updateCompiler$1.apply(JdbcProfile.scala:30)
at slick.jdbc.JdbcMappingCompilerComponent$JdbcCodeGen.compileServerSideAndMapping(JdbcMappingCompilerComponent.scala:59)

最佳答案

嗯...答案在于您正在尝试做一些 Slick 不应该做的事情。

一个非常简单的指南——当有疑问时用 SQL 思考然后转换为 Slick

想想你将如何在 SQL 中实现这一点,

如果我转换你的“查询”,

// lets say Host.name = "Awesome-Host"

active.filter(a => a.usedBy.isEmpty || a.usedBy === Host.name)
.take(10)
.map(account => account.usedBy)
.update(Option(Host.name))

对SQL来说,就是这样,

UPDATE
active
SET
used_by = 'Awesome-Host'
WHERE
used_by IS NULL
OR used_by = 'Awesome-Host'
LIMIT 10

从 SQL 的角度来看,这有点荒谬......

现在...让我们谈谈您将如何使用 SQL 实际执行此操作,

UPDATE
(
SELECT
*
FROM
active
WHERE
used_by IS NULL
OR used_by = 'Awesome-Host'
LIMIT 10
) active_selection
SET
active_selection.used_by = 'Awesome-Host'

并且...这可以使用子查询转换为 Slick

val activeSelection = active
.filter(a => a.usedBy.isEmpty || a.usedBy === Host.name)
.take(10)

val updateSelection = activeSelection
.map(a => a.usedBy)
.update(Option(Host.name))

关于scala - 在 slick 中更新表的前 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41311802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com