我想知道哪种更好用,是数据库 View 还是仅将字段保留在数据库中。
例如,我正在以下 View win_count
中初始化vw_stats
:
...
CASE
WHEN game.in_decision = true AND game.user_score > game.opponent_score THEN 1
ELSE 0
END AS win_count,
...
然后将其映射到域类:
package com.x
class Stat {
//fields here...
static mapping = {
table 'vw_stats'
version false
}
}
或者,是否应该使用此域类将字段
winCount
保留在数据库中并在保存之前对其进行操作?package com.x
class Game {
//fields here...
Short winCount = 0
static constraints = {
//constraints here...
winCount nullable: false, range: 0..99
}
def beforeInsert(){
this.beforeUpdate()
}
def beforeUpdate(){
//other manipulations here...
if inDecision and userScore > opponentScore
winCount = 1
}
}
我发现的 View 问题是,它将在运行应用程序时生成一个表,然后我必须手动删除该表并运行代码以生成 View 。
更新#1
通过将它们持久保存在数据库而不是 View 中,可能会节省IO成本?
更新#2
忘了提一下,我应该能够在服务的结果字段上应用聚合函数。
最佳答案
第三种方法是使用derived属性。与 View 一样,该值是动态计算的。
package com.x
class Game {
//fields here...
Short winCount = 0
static constraints = {
//constraints here...
winCount nullable: false, range: 0..99
}
static mapping = {
winCount formula: 'CASE WHEN in_decision = true AND user_score > opponent_score THEN 1 ELSE 0 END'
}
}
关于grails - 使用 View 或将其保留在数据库中的计算字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226795/