我有一个问题跟踪管理程序,我试图建立一个SQL查询来返回每个月的行数组。
我已经尝试使用while循环来循环并推送每个月后的行数长度。然而,它在循环完成之前就返回了数组。
我知道我也可以使用count()来获取行长,但我只需要获取1-6之间的月份。
有没有更简单的查询方法?
getMonthlyData(db, teamId){
let monthlyData = [];
let i = 1;
while (i < 6){
db
.from('issues')
.select('*')
.where({team_id: teamId})
.andWhereRaw(`EXTRACT(MONTH FROM date_created::date) = ?`, [i])
.then(rows => {
console.log('Monthly data')
console.log(rows);
monthlyData.push(rows.length)
})
.catch((e) => {
console.log(e);
})
}
return monthlyData;
}
谢谢你
相当于你的查询在修复了异步错误后,作为一个单一的查询应该是这样的。
async getMonthlyData(db, teamId) {
return db('issues')
.where({team_id: teamId})
.whereBetween(db.raw(`EXTRACT(MONTH FROM date_created::date)`), [1,6]);
}
另一种写法是用一个额外的列来告诉提取的月份..:
async getMonthlyData(db, teamId) {
// after this query you can easily group the resulted issues by month
return db('issues')
.select('*', db.raw(`EXTRACT(MONTH FROM date_created::date) as month`))
.where({team_id: teamId})
.whereBetween(month, [1,6]);
}