有上图这两个表,想查询出每本书的名称,进货次数(count(*)),数量 sum(quality)
写惯了sql语句,jql真不好写。
能够联表查询出所有数据,但这种count 和 sum 怎么写?
下面的查询语句能实现你的需求,另外quality是质量,quantity才是数量
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
const res = await db.collection('book').aggregate().lookup({
from: 'order',
localField: '_id',
foreignField: 'book_id',
as: 'order'
})
.project({
_id: true,
name: true,
inCount: $.size('$order'),
total: $.reduce({
input: '$order',
initialValue: 0,
in: $.sum(['$$value', '$$this.quality'])
})
})
.end()
或使用jql扩展
const dbJQL = uniCloud.databaseForJQL()
const book = dbJQL.collection('book').getTemp()
const order = dbJQL.collection('order').getTemp()
const res = await dbJQL.collection(book, order)
.field('name,size(_id.order) as inCount, reduce(_id.order, 0, sum("$$value","$$this.quality")) as total')
.get()