sql语句:借助count函数求总条数
select count(*) from classify
可以看到结果集内多了 count(*) 值为7 这一列 ,但这样 取值不能取
所以起个别名
select count(*) as total from classify
可以通过查询条件进行sql语句的拼接
const { query, order = 'asc', field, page = 0, size = 3 } = ctx.query
let sql = 'select * from classify'
let sql2 = 'select count(*)as total from classify'
if (query) {
sql += ` where name like '%${query}%'` //查询
sql2 += ` where name like '%${query}%'` //查询,求总数
}
if (field) {
sql += ` order by ${field} ${order} ` ///在结果集内-排序
}
sql += `limit ${page * size},${size}` //分页
const res = await doSQL(sql)
const res2 = await getOne(sql2) //我们只用处理一条数据,所以通过getOne拿到total
ctx.body = { success: true, code: 20000, message: '数据查询成功', data: res, total: res2.total };
res2.total就可以拿到total的值了