我正在尝试在 Knex.js 中重写一些 MySQL 查询,我感觉我每次都会遇到 .raw
,这感觉与我想在中使用 Knex 的原因背道而驰第一名。
是否可以在不使用 .raw
的情况下编写以下查询?
SELECT
product,
SUM(revenue)
FROM orders
使用 raw,可以这样写:
knex()
.select(
'product',
knex.raw('SUM(revenue)')
)
.from('orders')
但是使用 Knex 的想法是避免使用 MySQL 查询字符串,所以我希望还有另一种方法。或者每个人都只是在任何地方使用 .raw
,而我误解了某些东西?很有可能,我是新手。
最佳答案
您可以使用sum
方法。
sum — .sum(column|columns|raw) Retrieve the sum of the values of a given column or array of columns (note that some drivers do not support multiple columns). Also accepts raw expressions.
knex('users').sum('products') Outputs: select sum("products") from "users"
大概是这样的:
knex()
.select('product')
.sum('revenue')
.from('orders')
您应该根据您的具体情况进行调整。您可能需要使用 groupBy('product')
之类的方法来获取每个产品的总收入。
你真的应该检查一下 knex 的 documentation ,它非常好且直接,你绝对不应该一直使用 raw。
关于mysql - 在 Knex.js 中选择总和,而不使用 .raw,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56838457/