node.js - mysql如何通过knex查询今天和七天内的汇总数据
问题描述
具体实现是要在product表中查询出今天、七天和三十天内的产品数量,具体的sql语句已经写好了
select sum(inputer as productNum) from `product` where to_days(`createdAt`)= to_days(now());
但是在knex.js里面我这样写根本不对
return knex(’product’) .where({ inputer: user, deletedAt: null }) .andWhere(’to_days(add_time)’, ’=’, ’to_days(now())’) .sum(’inputer as productNum’) .then(function (productRow) { return { product: productRow }; })
用having也不对,knex文档里没有看到聚合函数的使用方法,求指教
return knex(’product’) .where({ inputer: user, deletedAt: null }) .groupBy(id) .having(’to_days(add_time)’, ’=’, ’to_days(now())’) .sum(’inputer as productNum’) .then(function (productRow) { return { product: productRow }; })
问题解答
回答1:没用过knex.js,但SQL好像复杂化了(原SQL会对createdAt字段进行运算,有可能会让该字段的索引失效)。
SELECT sum(inputer) AS product_num FROM `product`WHERE createdAt >= ?
通过程序计算出今天、七天前和三十天前的起始时间(即yyyy-MM-dd 00:00:00),然后代入SQL即可。
相关文章:
1. APP上传到电脑服务器,出现数据上传不完整的问题2. javascript - iframe 为什么加载网页的时候滚动条这样显示?3. tp 6.0 数据查询,求教!4. 柱形图12月显示不出来5. git - 使用淘宝npm安装hexo出现问题?6. javascript - html这种样式怎么做出来?7. javascript - nodejs 如何同步执行某些模块函数?8. java里自定义类重载ClassLoader有什么用?9. java - mongodb分片集群下,count和聚合统计问题10. html5 - <!doctype html public "storage"> 是什么意思
