gpt4 book ai didi

mysql - 水线 - 字段总和的位置

转载 作者:行者123 更新时间:2023-11-29 15:23:48 26 4
gpt4 key购买 nike

我有以下模型测试

module.exports = {
attributes: {
a: {
type: 'number'
},
b: {
type: 'number'
}
}
}

我想构建一个查询,允许我将字段 ab 的总和放入 where 语句中。

相当于 SQL:

SELECT * FROM Test WHERE a + b = myValue

我在 sails 文档中读到了关于 Criteria modifiers 的内容但没有任何相关消息。

有什么聪明的方法可以做到这一点吗?我当然可以使用native query但我想避免这种情况,因为我必须将总和与其他修饰符一起使用。原因是我从单独的文件生成动态查询,并且使用 native 查询我还必须处理已经定义的功能,例如 or、and 等。

最佳答案

我找到了解决方法。也许这对某人有用。它不是严格的 sails/node 解决方案,而是数据库解决方案,但是,它非常适合我的情况。

从 MySQL 5.7 开始,有类似 generated columns 的内容。 .

Columns are generated because the data in these columns are computed based on predefined expressions.

我所要做的就是向我的测试模型添加一个额外的自动生成的列:

module.exports = {
attributes: {
a: {
type: 'number',
columnType: 'int'
},
b: {
type: 'number',
columnType: 'int'
},
c: {
type: 'number',
columnType: 'int GENERATED ALWAYS AS(a + b) VIRTUAL'
}
}
}

现在我可以执行这样的查询:

const result = await Test.find({ c: 2 })

...我得到了正确的结果。 Waterline 像对待其他专栏一样对待我的专栏,数据库代替我完成所有事情。

当然,我可以将它与其他修饰符混合使用,没有任何问题。

到目前为止我还没有看到任何并发症。

关于mysql - 水线 - 字段总和的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59182326/

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